新建文件判断路径是否存在

File img = new File(SavePath);
if(img.getParentFile().exists())
{
doXXX();
}else{
img.getParentFile().mkdirs();
doXXX();
}
### Python 检查文件路径是否存在 在Python中,可以利用`os.path.exists()`来检查给定的路径是否存在。此方法返回布尔值,其中`True`表示路径存在,而`False`意味着路径存在[^3]。 ```python import os path_to_check = "D:\\numpy_project\\demo.py" if os.path.exists(path_to_check): print(f"The path {path_to_check} does exist.") else: print(f"The path {path_to_check} does not exist.") ``` 上述代码展示了如何通过指定路径变量`path_to_check`并调用`os.path.exists()`来进行简单检测。如果路径存在,则会输出相应的消息;反之亦然[^1]。 对于更复杂的逻辑需求,比如不仅想要知道路径存不存在还想处理当路径确实不存在的情况时自动创建它,那么可以根据实际业务编写更加详细的函数[^2]: ```python def check_and_create_directory(file_path): directory_name, _ = os.path.split(file_path) if not os.path.exists(directory_name): try: os.makedirs(directory_name) print(f"Directory created at '{directory_name}'.") except OSError as error_message: print(f"Failed to create directory due to an unexpected error: {error_message}") else: print(f"Directory already exists at '{directory_name}'.") check_and_create_directory("file/vide/dj/data.py") ``` 这段增强版的例子引入了一个新的辅助函数`check_and_create_directory()`, 它接受一个完整的文件路径作为参数,在确认父级目录缺失的情况下尝试建立新目录结构,并妥善处理可能发生的异常情况[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值