0

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')
RMPR
  • 3,368
  • 4
  • 19
  • 31
  • 3
    Use [`os.path.exists`](https://docs.python.org/3/library/os.path.html#os.path.exists), [`os.path.isfile`](https://docs.python.org/3/library/os.path.html#os.path.isfile), or [`os.path.isdir`](https://docs.python.org/3/library/os.path.html#os.path.isdir). – luuk Mar 16 '21 at 17:39

4 Answers4

3

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
RMPR
  • 3,368
  • 4
  • 19
  • 31
0

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
0

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.

Keine_Eule
  • 137
  • 8
0

Please to some search before post it.

import os.path
fname = "you_filename"
os.path.isfile(fname)
Nayan Biswas
  • 112
  • 1
  • 4