Python Forum

Full Version: How to write in text file - indented block
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I would like to open a text file in the loop and every time I would like to save a new line in the file but I have syntax error of "expected an indented block". How to fix that ?

i = 1
while i < 6:
f = open("readme.txt", "a")
f.write( str(i) + "\tHello\t" + "Now the file has more content!\n")
f.close()
i += 1
To fix it.
f = open("readme.txt", "a")
i = 0
while i < 6:
    f = open("readme.txt", "a")
    f.write( str(i) + "\tHello\t" + "Now the file has more content!\n")
    i += 1
    f.close()
I would not write it like this,code ove can be called unpytonic.
with open("readme.txt", "a") as f:
    for i in range(6):
        f.write(f'{i} \tHello\t Now the file has more content!\n')
So with open close file object automatically,for loop is better more readable than the while.
(Aug-09-2021, 12:08 PM)snippsat Wrote: [ -> ]To fix it.
f = open("readme.txt", "a")
i = 0
while i < 6:
    f = open("readme.txt", "a")
    f.write( str(i) + "\tHello\t" + "Now the file has more content!\n")
    i += 1
    f.close()
I would not write it like this, code ove can be called unpytonic.
with open("readme.txt", "a") as f:
    for i in range(6):
        f.write(f'{i} \tHello\t Now the file has more content!\n')
So with open close file object automatically,for loop is better more readable than the while.

I still get an error when I run the following code. I would like to write the serial data into the file.

import serial
ser = serial.Serial("COM7", 9600)
    while True:
    bs = ser.read(512)
    bs = bs.replace(b'\n', b' ').replace(b'\r', b' ')
    print(bs)
    f = open("readme.txt", "a")
    f.write( bs)
    f.close()
Please use python tags. I cannot tell if you error is that you don't indent, or if that is just an artifact of using "Block Quote" instead of "Insert python".

Please post your entire error message and trace, and post the code that crashed. The entire code. It is really annoying when the useful line numbers in the error trace do not match up with the provided code.
Even though it's been a while, I'm wondering where the bug was and if the fix provided here helped? I just wanted to use similar code for my essay search project on the topic and save them to a file through writing. I've already looked into having them from https://studymoose.com/free-essays/stakeholders on economics for example and even figured out how to copy them. But that's just if there are several of them it is more convenient through a loop, but the same error appears and thought there was already a solution.