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!

r.ook
  • 13,466
  • 2
  • 22
  • 39
salah
  • 106
  • 2
  • 12
  • 1
    Possible duplicate of [Read/Write text file](https://stackoverflow.com/questions/16604826/read-write-text-file) – Mat Mar 06 '19 at 19:49

1 Answers1

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)
Merig
  • 1,751
  • 2
  • 13
  • 18
  • 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 – salah Mar 06 '19 at 19:36
  • 1
    You can use os.rename('new_file', 'old_file') after the loop – Merig Mar 06 '19 at 19:41
  • 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`) – salah Mar 07 '19 at 13:14