首页 > 解决方案 > 如何在Python中查找特定文件是否存在于某处

问题描述

我写了这段代码来创建一个 txt 文件来写一些东西,但是我想如果这个文件存在来创建另一个文件:

with open(./example.txt, mode= 'w') as TFile:
    TFile.write('something')

标签: pythonpython-3.x

解决方案


处理路径时,最好使用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

推荐阅读