Home > Back-end >  Shorter version python code block , using file.write
Shorter version python code block , using file.write

Time:11-11

I am a beginner in python, wondering if there is shorter version to this code block.I am trying to write table of eight to file.

i = 1
file = open('table.txt', 'w')
while i<=10:
    inputf = str(8*i)
    file.write('8 * ')
    file.write(str(i))
    file.write(' = ')
    file.write(inputf)
    file.write('\n')
    i = i 1
file.close()

CodePudding user response:

You can use f-string like below:

i = 1
file = open('table.txt', 'w')
while i<=10:
    file.write(f' 8 * {i} = {8*i} \n')
    i = i 1
file.close()

By thanks @BNilsou With for-loop:

file = open('table.txt', 'w')
for i in range(1,11):
    file.write(f' 8 * {i} = {8*i} \n')
file.close()

Output: (in table.txt)

 8 * 1 = 8 
 8 * 2 = 16 
 8 * 3 = 24 
 8 * 4 = 32 
 8 * 5 = 40 
 8 * 6 = 48 
 8 * 7 = 56 
 8 * 8 = 64 
 8 * 9 = 72 
 8 * 10 = 80 

CodePudding user response:

with open("table.txt", "w") as file:
    for i in range(1, 11):
        print(f'8 * {i} = {8 * i}', file=file)

is about the shortest in lines you can get.

CodePudding user response:

You'll get the same result with:

with open('table.txt', 'w') as fh:
    for i in range(1, 11):
        fh.write(f'8 * {i} = {8*i}\n')

CodePudding user response:

file = open('table.txt', 'w')
for i in range(1, 11):
    statement = '8 * '   (str(i))   ' = '   str(8*i)   '\n'
    file.write(statement)
file.close()

CodePudding user response:

Change all the write lines and convert it to one: file.write("8*",i,"=",inputf,"\n")

CodePudding user response:

open("table.txt", "w").write("\n".join([f'8 * {i} = {8 * i}' for i in range(1, 11)]))

It's the shortest way, but it's very bad way :)

  • Related