1

I have a txt file that I need to read and find a line, and change its value inside the same file. I am using Python.

for file in os.listdir(path2):
    if file.startswith('nasfla.in'):
        crack_in = ''.join((path2, '\\', file))
        file_in = open(crack_in, 'r')
        with file_in:
            for line in file_in:
                #looking for the line that I need to change
                if (str(line[1:11])) == 'schedcount':
                # change the line with new value 

I would like to change what is in the line that starts with 'schedcount' but I don't know how to read and write in file in same time.

Thanks!

1
  • 1
    Possible duplicate of Read/Write text file Commented Mar 6, 2019 at 19:49

1 Answer 1

3

Updating lines while iterating is tricky, you're better off rewriting the file if it's not too big:

with open('old_file', 'r') as input_file, open('new_file', 'w') as output_file:
    for line in input_file:
        if 'schedcount' in line:
            output_file.write('new line\n')
        else:
            output_file.write(line)
Sign up to request clarification or add additional context in comments.

3 Comments

just one question there is no way that I can keep the same name of file because I need the file as an input for a subprocess and if I change the file name the subprocess will stop
You can use os.rename('new_file', 'old_file') after the loop
Just to reminde people before you rename the new file with name of the old file dont forget to remove the old file from the directory or it will fail use os.remove(old file)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.