要创建一个文件,请使用 open() 函数并指定 filename 和 mode。mode 应为 "w"(写入模式)或 "x"(独占创建模式)。使用 write() 方法写入文件,并使用 close() 方法关闭文件,以释放资源并防止数据丢失。

如何在 Python 中创建一个文件
打开要创建的文件
要创建一个新的文件,需要使用 Python 的 open() 函数并指定文件名。open() 函数返回一个文件对象。
语法:
立即学习“Python免费学习笔记(深入)”;
<code class="python">file_object = open(filename, mode)</code>
参数:
-
filename: 要创建的文件名。 -
mode: 指定以何种模式打开文件。对于创建新文件,可以指定以下模式:-
w: 写入模式 (覆盖现有文件或创建新文件) -
x: 独占创建模式 (仅当文件不存在时才创建新文件)
-
示例:
创建名为 newfile.txt 的新文件:
<code class="python">file_object = open("newfile.txt", "w")</code>写入文件
使用 write() 方法将数据写入文件。
语法:
立即学习“Python免费学习笔记(深入)”;
<code class="python">file_object.write(data)</code>
参数:
-
data: 要写入文件的数据。
示例:
<code class="python">file_object.write("Hello, world!")</code>关闭文件
使用 close() 方法关闭文件,释放系统资源。如果不关闭文件,可能会导致数据丢失。
语法:
立即学习“Python免费学习笔记(深入)”;
<code class="python">file_object.close()</code>
示例:
<code class="python">file_object.close()</code>
完整示例:
<code class="python">file_object = open("newfile.txt", "w")
file_object.write("Hello, world!")
file_object.close()</code>











