我有一个txt文件,需要读取和查找一行,并在同一文件内更改其值。我正在使用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
我想更改以'schedcount'
开头的行中的内容
但是我不知道如何同时读写文件。
谢谢!
答案 0 :(得分:3)
在迭代时更新行比较棘手,如果文件太大,最好重写文件:
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)