Home > Mobile >  a command in python reads but does not append
a command in python reads but does not append

Time:11-02

For example, I have a text file that contains 4 lines of this statement "this is shirin" when I run the following code nothing happens on my file:

file = open('test.txt', 'a ')
for i in file:
    if len(i) == 0 or 'this' in i:
        file.write('test')
file.close()

CodePudding user response:

When you open the file in append mode, the initial position is at the end, so there's nothing to read and the loop ends immediately. You need to rewind to the beginning of the file to read. And if you want to keep reading, you need to seek again after writing at the end.

with open('test.txt', 'a ') as file:
    file.seek(0)
    while True:
        i = file.readline()
        if not i:
            break
        oldpos = file.tell()
        if 'this' in i:
            file.write('test')
            file.seek(oldpos)
  • Related