在python中追加现有文件的行

这个问题在这里已经有了答案:

  • 你如何追加到一个文件? 8个答案

  • 问题出在代码中 -

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

    第二个参数应该是一个字符串,它表示文件应该被打开的模式,你应该使用a which来表示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')

    链接地址: http://www.djcxy.com/p/42405.html

    上一篇: Appending lines for existing file in python

    下一篇: How do you append to a file?