将数据添加到现有文件python的末尾

Jim*_*asa 4 python file-io

所以我的代码看起来像这样....但我想总是在文档的末尾添加数据我将如何做到这一点

try:
    f = open("file.txt", "w")
    try:
        f.write('blah') # Write a string to a file
        f.writelines(lines) # Write a sequence of strings to a file
    finally:
        f.close()
except IOError:
    pass
Run Code Online (Sandbox Code Playgroud)

Thi*_*ter 14

使用'a'(append)而不是'w'(write,truncate)打开文件

除此之外,您可以执行以下操作而不是try..finally块:

with open('file.txt', 'a') as f:
    f.write('blah')
    f.writelines(lines)
Run Code Online (Sandbox Code Playgroud)

with块自动关闭在块结束时关闭文件.