0

I would like to avoid accidental replacement, when I create a new file.

My code is this to check file name.

fname = "myFile"
contents = "abc"

if fname is existing:  #How to check this?

    print("The file name is already existing, would you want to replace the file?")
    myAnswer = input("The answer is : ")
    print("Your answer is " + myAnswer)

    if myAnswer == "yes":
        fid = open(fname,'w')
        fid.write(contents)
        fid.close()
    else:
        print("rejected")

else:
    fid = open(fname, 'w')
    fid.write(contents)
    fid.close()

But, I don't know how to scan file name in a folder.

Anyone can help me?

KKS
  • 1,389
  • 1
  • 14
  • 33

1 Answers1

0

You could use the os library:

import os
os.path.isfile(fname)

Returns True if a path to the file exists or is a symbolic link.