为 python 中的现有文件追加行

Appending lines for existing file in python

我想向 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 我没有得到我添加的新行。我该如何解决?

问题出在代码中-

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 ,它将用新内容覆盖现有文件,它不会追加到文件末尾。

上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')