0

当我创建一个新文件时,我想避免意外替换。

我的代码是检查文件名。

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

但是,我不知道如何扫描文件夹中的文件名。

任何人都可以帮助我吗?

4

1 回答 1

0

您可以使用该os库:

import os
os.path.isfile(fname)

返回True文件的路径是否存在或者是符号链接。

于 2019-08-13T08:04:05.833 回答