Reputation: 106
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!
Upvotes: 1
Views: 443
Reputation: 2011
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)
Upvotes: 3