Python 创建文件和目录方法:实现文件类型判断及异常处理
import os
def create_file(file_type, file_path):
'''
创建文件或目录
Args:
file_type (str): 文件类型,'目录' 或 '文件'
file_path (str): 文件路径
Returns:
int: 创建结果,1 表示创建目录成功,2 表示创建文件成功,3 表示创建失败
'''
if file_type == '目录':
try:
os.makedirs(file_path)
return 1
except:
return 3
elif file_type == '文件':
try:
with open(file_path, 'w') as f:
f.write('')
return 2
except FileNotFoundError:
dir_path = os.path.dirname(file_path)
try:
os.makedirs(dir_path)
with open(file_path, 'w') as f:
f.write('')
return 2
except:
return 3
else:
return 3
注意事项:
-
创建文件时需要指定打开模式为'w',表示写入模式。如果文件已经存在,会清空文件内容。如果文件不存在,则会创建文件并写入空字符串。
-
创建文件时,如果文件所在的目录不存在,需要使用
os.path.dirname()方法获取文件所在目录的路径,然后使用os.makedirs()方法创建目录。 -
在创建文件或目录的过程中,可能会出现各种异常,需要使用
try...except语句进行异常处理。 -
如果创建成功,返回数字1或2;如果创建失败,返回数字3。
原文地址: https://www.cveoy.top/t/topic/ngGU 著作权归作者所有。请勿转载和采集!