【问题标题】:Appending lines for existing file in python [duplicate]在python中为现有文件附加行[重复]
【发布时间】:2015-06-17 18:48:11
【问题描述】:

我想在 python 中的现有文件中添加行。我写了以下两个文件

print_lines.py

while True:
    curr_file = open('myfile',r)
    lines = curr_file.readlines()
    for line in lines:
        print lines

add_lines.py

curr_file = open('myfile',w)
curr_file.write('hello world')
curr_file.close()

但是当我先运行 print_lines.py 然后运行 ​​add_lines.py 时,我没有得到我添加的新行。我该如何解决?

【问题讨论】:

  • 代码中存在语法错误。 open() 接受字符参数,例如 open('myfile', 'w')
  • open('myfile', 'w') 应该以附加模式打开文件open('myfile','a')

标签: python file python-2.7 io


【解决方案1】:

问题出在代码中 -

curr_file = open('myfile',w)
curr_file.write('hello world')
curr_file.close()

第二个参数应该是一个字符串,表示打开文件的模式,你应该使用a,表示append

curr_file = open('myfile','a')
curr_file.write('hello world')
curr_file.close()

w 模式表示write,它会用新内容覆盖现有文件,它不会追加到文件末尾。

【讨论】:

    【解决方案2】:

    在 print_lines.py 上:

    1 - 你一直在循环,while True,你需要添加一个中断条件来退出 while 循环或删除 while 循环,因为你有 for 循环。

    2 - curr_file = open('myfile',r) 的参数 2 必须是字符串:curr_file = open('myfile','r')

    3 - 在最后关闭文件:curr_file.close()

    现在在 add_lines 中:

    1 - 如果要添加行,则打开文件进行追加而不是覆盖:curr_file = open('myfile','a')

    2 - 与上一个文件相同,myfile = open('myfile',w) 的参数 2 必须是字符串:curr_file = open('myfile','a')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 2018-11-06
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      相关资源
      最近更新 更多