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')
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)