如何用 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()方法将内容写入文件。











