Python 文件读写的基本使用
【摘要】 Python 文件读写的基本使用Python 可以使用 open() 函数读取或写入本地文件,适合处理日志、配置文件和文本数据。读取文件with open("data.txt", "r", encoding="utf-8") as file: content = file.read() print(content)写入文件with open("data.txt", "w", en...
Python 文件读写的基本使用
Python 可以使用 open() 函数读取或写入本地文件,适合处理日志、配置文件和文本数据。
读取文件
with open("data.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
写入文件
with open("data.txt", "w", encoding="utf-8") as file:
file.write("Hello Python")
追加内容
如果不想覆盖原有内容,可以使用 a 模式:
with open("data.txt", "a", encoding="utf-8") as file:
file.write("\n新增一行内容")
使用 with open() 可以在操作完成后自动关闭文件,是 Python 中比较推荐的文件处理方式。
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)