面试题答案
一键面试在Python中,使用open()
函数以写入模式打开文件时,如果文件所在目录不存在,会引发FileNotFoundError
。
以下是捕获并处理该错误,以创建目录并成功写入文件的代码示例:
import os
file_path = 'your_directory/your_file.txt'
try:
with open(file_path, 'w') as f:
f.write('Some content')
except FileNotFoundError:
os.makedirs(os.path.dirname(file_path))
with open(file_path, 'w') as f:
f.write('Some content')