Skip to content Skip to sidebar Skip to footer

How Can I Change One Line In Text File With Python

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.

Solution 1:

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)

Post a Comment for "How Can I Change One Line In Text File With Python"