如何使用 Python 保存 TXT 文件?导入 os 和 io 模块。创建或打开一个 TXT 文件。使用 write() 方法写入文件内容。写入完成后,关闭文件。

如何使用 Python 保存 TXT 文件
步骤 1:导入 os 和 io
首先,导入以下两个模块:
<code class="python">import os import io</code>
步骤 2:创建或打开文件
立即学习“Python免费学习笔记(深入)”;
使用以下代码创建一个新的 TXT 文件或打开一个现有的文件:
<code class="python">with io.open('new_file.txt', 'w', encoding='utf-8') as file:
# 在此写入文件内容</code>步骤 3:写入文件
您可以使用 write() 方法将内容写入文件:
<code class="python">file.write('Hello, world!\n')</code>步骤 4:关闭文件
写入完成后,使用以下代码关闭文件:
<code class="python">file.close()</code>
示例代码
<code class="python">import os
import io
# 创建或打开文件
with io.open('new_file.txt', 'w', encoding='utf-8') as file:
# 写入内容
file.write('Hello, world!\n')
file.write('This is a new line.\n')
# 关闭文件
file.close()</code>其他提示
utf-8)以支持非 ASCII 字符。with 语句来简化文件操作,它将自动关闭文件。open() 函数,它返回一个文件对象,需要手动关闭。以上就是python怎么保存txt文件的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号