在Python中将文本附加到文件 [英] Append a text to file in Python

查看:186
本文介绍了在Python中将文本附加到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 如何检查文件是否存在?

  2. 如何在文件中附加文字?

我知道如何创建文件,但在这种情况下,它会覆盖所有数据:

I know how to create the file, but in this case, it overwrites all data:

import io

with open('text.txt', 'w', encoding='utf-8') as file:
    file.write('text!')

* nix 我可以做类似的事情:

In *nix I can do something like:

#!/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 附加到文件:

Use mode a instead of w to append to the file:

with open('text.txt', 'a', encoding='utf-8') as file:
    file.write('Spam and eggs!')

这篇关于在Python中将文本附加到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆