【发布时间】:2012-03-07 00:59:09
【问题描述】:
- 如何检查文件是否存在?
- 如何将文本附加到文件中?
我知道如何创建文件,但在这种情况下,它会覆盖所有数据:
import io
with open('text.txt', 'w', encoding='utf-8') as file:
file.write('text!')
在*nix 我可以做类似的事情:
#!/bin/sh
if [ -f text.txt ]
#If the file exists - append text
then echo 'text' >> text.txt;
#If the file doesn't exist - create it
else echo 'text' > text.txt;
fi;
【问题讨论】:
-
open('text.txt', 'a', encoding='utf-8') -
这似乎是 Python 3.x,因为您使用
encoding参数到open()。对吗? -
我用搜索,找不到答案!