在Python中向文件追加文本 如何检查文件是否存在 如何将文本附加到文件中
我知道如何创建文件,但在这种情况下,它会覆盖所有数据:在Python中向文件追加文本 如何检查文件是否存在 如何将文本附加到文件中,python,io,Python,Io,我知道如何创建文件,但在这种情况下,它会覆盖所有数据: 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;
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;
使用模式
a
而不是w
附加到文件:
with open('text.txt', 'a', encoding='utf-8') as file:
file.write('Spam and eggs!')
至于你的第一个问题,谷歌搜索将出现几种方式。请尝试前面的问题:
open('text.txt','a',encoding='utf-8')
这似乎是Python 3.x,因为您使用encoding
参数来open()
。对吧?我用搜索法找不到答案!谢谢,我找不到钥匙-a
。请告诉我,如何检查文件是否存在?为什么要检查文件是否存在?只有当它还不存在时,你才会附加它,这是没有意义的吗?@Wooble,我只是想知道怎么做。*nix的解决方案之一是:如果os.path.存在(文件名):
因此答案应该是自包含的,所以请在答案中的链接页面中提供最重要的信息——有关详细信息,请参阅。是否有任何方法可以检查没有os
(我需要win/nux平台)的文件?os
模块尽可能是可移植的<代码>os.path.isfile()包括在内