Home > Enterprise >  for loop used to append a file in python but that didnt work
for loop used to append a file in python but that didnt work

Time:08-08

below is a code to append a file if a condition is met in for loop but this code doesnot print anything in the given text file. where is the error . the condition is met

with open("rollNameList.txt","a ") as file:
    for line  in file:
        if line in "george\n":
            file.write("george is tall and strong")

the text file consist of this name

george
ford 
black
reacher
tom
robert
chris
ben
mike
jasmine

CodePudding user response:

Your issue is opening the file in a . When opening a file in "a" or "append" mode, you will automatically seek to the end. You can check it like this:

with open("file.txt", "a ") as f:
    print(f.tell())
    # Prints 213
    print(repr(f.read())
    # will print ""

This will return a big number, the exact length of the file. There are 2 ways to fix this, using seek or using a different mode.

Using Seek

First, using seek would look like this:

with open("file.txt", "a ") as f:
    f.seek(0)
    print(f.read())
    f.write("bla")

This will print the contents of the file. Other methods like readlines will also work.

Using r opening mode

The other way is using r instead:

with open("file.txt", "r ") as f:
    print(f.read())
    f.write("bla")

The r mode is pretty much the same as a except the cursor will start at the start of the file.

In any of these examples you can replace f.read() with for line in f or f.readlines() or any other file method.

Writing to the file inside a loop

As @joanis pointed out in the comments it's impossible to use seek and tell while the readlines loop is running. So it would be best to store the lines you want to write in a list and write them to the file at the very end.

Where you write in the file will also be effected by the cursor, you may want to seek() to the end of the file before writing and then seek() back afterwards

CodePudding user response:

Hi since your question is not clear, I will try to my best to answer.

First I would suggest reading your text file and assign it to variable with below;

with open("rollNameList.txt","r") as file: 
    file_content = file.read()

Now you will have your content into a list like below;

["george","ford"]

Then with this simeple for loop you can check if "george" is in your file_content;

if "george" in file_content :
    print("george is tall and strong")

And if you want to change text to something else if "george" is present;

name_list = ["george", "ford"]


for i in range(0,len(name_list)) :
    if name_list[i] == "george":
        name_list[i] = "george is tall"
    else:
        pass

print(name_list)

At last you can write updated list into text file.

  • Related