import os
def check_and_create_file(file_path):
# 检查文件是否存在
if not os.path.exists(file_path):
# 如果文件不存在,则创建文件
with open(file_path, 'w') as file:
file.write('') # 创建一个空文件
print(f"文件 {file_path} 已创建")
else:
print(f"文件 {file_path} 已存在")
# 示例调用
check_and_create_file('example.txt')
os
模块提供了与操作系统交互的功能,这里用来检查文件是否存在。check_and_create_file(file_path)
函数接收一个文件路径作为参数。os.path.exists(file_path)
检查文件是否存在。如果文件不存在,返回 False
,否则返回 True
。open(file_path, 'w')
打开文件并写入一个空字符串,从而创建一个空文件。通过这个代码片段,你可以轻松地检查文件是否存在,并在文件不存在时创建它。
上一篇:python串口发送16进制数据
下一篇:python截取指定位置的字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站