python - 如何在Python中查找特定文件是否存在于某处
问题描述
我写了这段代码来创建一个 txt 文件来写一些东西,但是我想如果这个文件存在来创建另一个文件:
with open(./example.txt, mode= 'w') as TFile:
TFile.write('something')
解决方案
处理路径时,最好使用pathlib
:
from pathlib import Path
example_file = Path("./example.txt")
if example_file.exists():
example_file = Path("./example2.txt")
with open(example_file, mode="w") as TFile:
# Do whatever
推荐阅读
- php - 致命错误:不能使用“对象”作为类名,因为它是保留的
- javascript - React Native 方法中的参数
- python - 基于python中的部分字符串匹配加入数据帧
- reactjs - 如何在reactJS中导入带参数的导出默认功能?
- laravel - 在 nem 中发起事务返回 FAILURE_WRONG_NETWORK
- ios - 在 AWS 套接字 S3 存储桶中缓存
- javascript - 如何通过单击javascript更改div?
- python - 使用带有 Pythonnet 的 mXparser 的构造函数错误
- html - 我可以在字体列表中使用 CSS 变量并让它在旧版浏览器中工作吗?
- python - 在 Excel 输出中动态调整行高:在单元格中添加了额外的行?