简体   繁体   中英

How to find if a specific file is existing somewhere or not in Python

I wrote this code that create a txt file to write something, but I want if this file exist to create another file:

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

When dealing with paths, it's better to use 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

If (when the file doesn't exist) you want to create it as empty, the simplest approach is

path='somepath'
with open(path, 'a'): pass

Here is a simple example how to check whether a file exists, and create a new file if yes:

import os
filename = './example.txt'

if os.path.isfile(filename):
    # This adds "-1" to the file name
    with open(filename[:-4] + '-1' + filename[-4:], mode= 'w') as TFile:
        TFile.write('something')
else:
    with open(.filename, mode= 'w') as TFile:
        TFile.write('something')

Of course you could change the way the new filename is chosen.

Please to some search before post it.

import os.path
fname = "you_filename"
os.path.isfile(fname)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM