如何用 Python 读写 TXT 文件?读取 TXT 文件:导入库:import os打开文件:with open("text.txt", "r") as f: content = f.read()写入 TXT 文件:导入库:import os创建文件:if not os.path.exists("text.txt"): open("text.txt", "w").close()打开文件:with open("text.txt", "w") as f: f.write("内容")

如何用 Python 读写 TXT 文件
读取 TXT 文件
导入 Python 库:
<code class="python">import os</code>
打开文件:
立即学习“Python免费学习笔记(深入)”;
<code class="python">with open("text.txt", "r") as f:
content = f.read()</code>"text.txt" 是要读取的文件名。"r" 表示打开文件用于读取。with 语句确保在退出语句块时自动关闭文件。content 变量现在包含文件的内容。写入 TXT 文件
导入 Python 库:
<code class="python">import os</code>
创建一个要写入的文件,如果不存在:
<code class="python">if not os.path.exists("text.txt"):
open("text.txt", "w").close()</code>打开文件:
立即学习“Python免费学习笔记(深入)”;
<code class="python">with open("text.txt", "w") as f:
f.write("这是要写入的文件内容。")</code>"text.txt" 是要写入的文件名。"w" 表示打开文件用于写入。with 语句确保在退出语句块时自动关闭文件。f.write() 方法将内容写入文件。以上就是python怎么读写txt的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号