So my code looks like this .... but I want to add data always to the end of the document how would I do this
所以我的代码看起来像这样....但我想在文档的末尾添加数据,我该怎么做
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
2 个解决方案
#1
13
Open the file using 'a'
(append) instead of 'w'
(write, truncate)
使用'a'(append)而不是'w'打开文件(write,truncate)
Besides that, you can do the following isntead of the try..finally
block:
除此之外,您可以执行以下操作而不是try ..finally块:
with open('file.txt', 'a') as f:
f.write('blah')
f.writelines(lines)
The with
block automatically takes care about closing the file at the end of the block.
with块自动关注在块结束时关闭文件。
#2
4
open the file with "a" instead of "w"
用“a”而不是“w”打开文件
#1
13
Open the file using 'a'
(append) instead of 'w'
(write, truncate)
使用'a'(append)而不是'w'打开文件(write,truncate)
Besides that, you can do the following isntead of the try..finally
block:
除此之外,您可以执行以下操作而不是try ..finally块:
with open('file.txt', 'a') as f:
f.write('blah')
f.writelines(lines)
The with
block automatically takes care about closing the file at the end of the block.
with块自动关注在块结束时关闭文件。
#2
4
open the file with "a" instead of "w"
用“a”而不是“w”打开文件