在Python中,你可以使用 `os.path.exists()` 方法来检查文件是否存在。以下是使用该方法的步骤:
1. 导入 `os` 模块。
2. 调用 `os.path.exists()` 方法,并传入文件路径作为参数。
3. 如果文件存在,该方法返回 `True`;否则返回 `False`。
示例代码如下:
```python
import os
file_path = "path/to/your/file.txt"
if os.path.exists(file_path):
print("文件存在")
else:
print("文件不存在")
你还可以使用 `os.path.isfile()` 方法来检查指定路径是否为文件,以及 `os.path.isdir()` 方法来检查是否为目录。
```python
import os
file_path = "path/to/your/file.txt"
if os.path.isfile(file_path):
print("这是一个文件")
elif os.path.isdir(file_path):
print("这是一个目录")
else:
print("这既不是文件也不是目录")