检查路径是否存在和路径下文件是否存在,不存在进行创建路径和文件 随意命名
时间: 2024-03-27 18:37:28 浏览: 13
好的,那我就以路径 `./data/test/` 以及文件名 `test.txt` 为例。以下是实现的 Python 代码:
```python
import os
path = './data/test'
filename = 'test.txt'
if not os.path.exists(path):
os.makedirs(path)
print(f'创建路径 {path} 成功')
file_path = os.path.join(path, filename)
if not os.path.exists(file_path):
with open(file_path, 'w') as f:
print(f'创建文件 {file_path} 成功')
else:
print(f'文件 {file_path} 已存在')
```
这里使用了 Python 的 `os` 模块来进行路径和文件的创建和检查,具体实现如下:
1. 首先使用 `os.path.exists()` 方法来检查路径是否已经存在,如果不存在则使用 `os.makedirs()` 方法来创建路径。
2. 然后使用 `os.path.join()` 方法将路径和文件名拼接起来,得到完整的文件路径。
3. 再次使用 `os.path.exists()` 方法来检查文件是否已经存在,如果不存在则使用 `open()` 函数创建文件,其中 `w` 参数表示以写入模式打开文件。
4. 如果文件已经存在,则直接输出提示信息。
这样就能够实现你的要求了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)