Python 字符串写入txt文件 四种常用方法
方法1:open() + write()(基础写法,需手动关闭文件)
# 待写入的字符串text = ”Hello Python,写入文本文件\n第二行内容”# 打开文件,w模式:覆盖原有内容,不存在则新建f = open(”test.txt”, ”w”, encoding=”utf-8”)f.write(text)# 写入字符串f.close()# 必须关闭,否则内容可能没保存
方法2:with 上下文管理器(推荐!自动关闭文件,最常用)
with 会自动释放文件资源,不用手动 close(),不会丢失数据
2.1 覆盖写入(w)
content = ”今天学习Python文件操作\n字符串存txt”# w = write,覆盖文件原有全部内容withopen(”demo.txt”, ”w”, encoding=”utf-8”) asfile: file.write(content)
2.2 追加写入(a,不覆盖,在末尾添加)
add_text = ”\n这一行是追加的新文字”# a = append 追加模式withopen(”demo.txt”, ”a”, encoding=”utf-8”) asfile: file.write(add_text)
方法3:writelines() 写入多行字符串列表
适合多行文本,注意:不会自动换行,需要手动加 \n
lines = [”第一行文字\n”, ”第二行文字\n”, ”第三行文字”]with open(”lines.txt”, ”w”, encoding=”utf-8”) as f: f.writelines(lines)
方法4:print() 直接输出到文件
s = ”使用print写入txt文件”with open(”print_txt.txt”, ”w”, encoding=”utf-8”) as f: print(s, file=f)
关键参数说明
a:追加,在文件末尾新增内容,不删除旧内容
完整示例:中文字符串写入
# 中文字符串msg = ”””Python写入txt测试第一行中文第二行中文”””# 写入文件with open(”中文测试.txt”, ”w”, encoding=”utf-8”) as f: f.write(msg)