【问题标题】:Read file line by line and add something new to each one逐行读取文件并为每个文件添加新内容
【发布时间】:2017-11-03 01:31:50
【问题描述】:

我知道之前有人问过类似的问题,但我是 python 新手,我找不到解决问题的方法:

我想做的是: 1. 打开一个文件,逐行读取。 (我已经设法做到了) 2. 在每一行之后添加一些新内容。 (我想稍后将它与 if 语句结合起来,以便只编辑特定的行)

我的代码:

#!/usr/bin/python3.4

file = open('testfile', 'r+')

readlinebyline = file.readline()

for i in range(0, len(readlinebyline)):
 readlinebyline.write(' ' + 'checked')

print('done')

我希望我的测试文件之后看起来像这样:

line1 checked
line2 checked
line3 checked
...

但它看起来像这样:

line1
line2
line3
 checked checked checked

如何让程序在每行之后停止,然后添加新内容?

【问题讨论】:

  • 您不是逐行阅读,而是一次阅读整个文件,而且您提供的代码会产生几个错误。
  • 代码没有产生任何错误。抱歉,我没有使用 testfile.readlines()。我使用了 testfile.readline()。如果这有所作为。刚刚编辑了
  • 是的。它将产生一个NameError,因为没有定义testfile,即使它,那么for i in range(0, len(readlinebyline()): 会抛出一个TypeError,因为列表对象是不可调用的。甚至除此之外,readlinebyline.write 会抛出 AttributeError,因为列表对象没有 write 属性。
  • 但基本上,如果您有能力将整个文件读入内存,最简单的方法是将其全部读入内存(作为您所做的列表),然后截断文件,然后随心所欲地写出来。
  • 用修改后的文件创建一个新文件几乎总是比尝试修改您正在阅读的文件更好。当然,一旦新文件关闭,如果您愿意,您可以轻松地用它替换原始文件。这样工作不仅更简单,而且更安全:如果你的机器在你的代码运行时崩溃或断电,你的数据不会被破坏。

标签: python


【解决方案1】:

您可以使用readlines

with open('testfile', 'r') as file:
    # read a list of lines into data
    lines = file.readlines()

with open('testfile', 'w') as file:
    for line in lines:
        # do your checks on the line..
        file.write(line.strip() + ' checked' )

print('done')

【讨论】:

    【解决方案2】:
    with open('file.txt', 'r') as f:
        content = f.readlines()
    
    with open('file.txt', 'w') as f:
        for line in content:
            f.write(line.strip('\n') + ' checked\n')
    

    【讨论】:

    • 最简单的解决方案。
    • 谢谢,这正是我所需要的。它工作正常。但我还不完全理解“line.strip('\n')”部分。 strip 方法似乎从行中删除特定字符。那么在这种情况下,它是否会在每次迭代中删除空白空间?对不起,我还是菜鸟。一个答案将不胜感激。我真的很想了解这个
    • 不,它只删除'\n',即每行末尾的换行符,因此您可以在同一行中添加'checked\n'。
    【解决方案3】:

    我建议逐行将文件写入一个新文件,然后将该新文件移动到将覆盖它的原始文件:

    import shutil
    
    filename = '2017-11-02.txt'
    temp_filename = 'new.txt'
    
    with open(filename, 'r') as old, open(temp_filename, 'w') as new:
        # Go line by line in the old file
        for line in old:
            # Write to the new file
            new.write('%s %s\n' % (line.strip(),'checked'))
    
    shutil.move(temp_filename, filename)
    

    我基于此的一些相关答案:https://stackoverflow.com/a/16604958/5971137

    【讨论】:

      【解决方案4】:
      testfile=open('uat_config.conf', 'r+')
      readlinebyline=testfile.readlines()
      for i in range(0, len(readlinebyline)):
       testfile.write("CHECKED "+ str(readlinebyline[i]))
      print('done')
      

      【讨论】:

      • 这回答了问题,但不会关闭文件并且不符合 PEP8。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 2021-10-18
      相关资源
      最近更新 更多