在Python中创建文件主要通过open()
函数、with
语句、os
和pathlib
模块实现,其中with open()
是最推荐的方式,因其自动管理文件资源且代码简洁。 以下是具体方法和注意事项:
-
open()
函数
使用open('文件名', 'w')
可创建新文件(若文件存在则覆盖),'a'
模式则追加内容。需手动调用close()
关闭文件,否则可能引发资源泄漏。例如:python复制
file = open('test.txt', 'w') file.write('内容') file.close()
-
with
语句
结合open()
的上下文管理器,操作结束后自动关闭文件,避免遗漏。例如:python复制
with open('test.txt', 'w') as file: file.write('内容')
-
os
模块
适用于需要检查文件是否存在或设置权限的场景。例如:python复制
import os if not os.path.exists('test.txt'): with open('test.txt', 'w') as file: file.write('内容')
-
pathlib
模块
Python 3.4+推荐使用,提供面向对象的路径操作。例如:python复制
from pathlib import Path Path('test.txt').write_text('内容')
-
临时文件
使用tempfile
模块创建生命周期短的临时文件:python复制
import tempfile with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.write(b'临时内容')
提示: 优先选择with open()
确保代码健壮性,涉及复杂路径时用pathlib
更直观。处理敏感操作需添加异常捕获(如权限错误)。