1、判断C:/my/1.txt文件是否存在 2、如果不存在,创建my目录,创建1.txt 用python
时间: 2024-01-20 22:03:03 浏览: 25
可以使用Python的os模块来判断文件是否存在,并在文件不存在时创建文件和目录。以下是示例代码:
```python
import os
file_path = 'C:/my/1.txt'
if not os.path.exists(file_path):
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'w') as f:
f.write('Hello, world!')
print(f'文件 {file_path} 创建成功!')
else:
print(f'文件 {file_path} 已经存在!')
```
代码中,首先定义了要创建的文件路径 `file_path`。然后使用 `os.path.exists()` 方法判断该文件是否存在。如果文件不存在,则使用 `os.makedirs()` 方法创建目录,使用 `open()` 方法创建文件并写入内容,最后打印创建成功的提示信息;如果文件已经存在,则直接打印文件已经存在的提示信息。
需要注意的是,在创建目录时,为了避免出现目录已经存在的错误,使用了 `exist_ok=True` 参数。在Python 3.2以后的版本中,该参数默认为True,表示如果目录已经存在,则不会抛出异常。