简体   繁体   中英

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.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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM