【问题标题】:How can I change one line in text file with python如何用python更改文本文件中的一行
【发布时间】:2019-07-28 13:13:57
【问题描述】:

我有一个 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' 开头的行中的内容 但我不知道如何同时读写文件。

谢谢!

【问题讨论】:

标签: python


【解决方案1】:

迭代时更新行很棘手,如果文件不太大,最好重写文件:

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)

【讨论】:

  • 只有一个问题,我无法保留相同的文件名,因为我需要该文件作为子进程的输入,如果我更改文件名,子进程将停止
  • 循环后可以使用 os.rename('new_file', 'old_file')
  • 只是提醒人们在用旧文件的名称重命名新文件之前不要忘记从目录中删除旧文件,否则使用 os.remove(old file) 会失败
猜你喜欢
  • 2019-04-12
  • 2022-11-30
  • 2017-04-14
  • 2015-05-31
  • 2022-01-21
  • 2021-09-05
  • 2013-05-13
  • 1970-01-01
  • 2016-05-25
相关资源
最近更新 更多