Python如何扫描文件是否已经存在?

2024-09-28 21:53:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望在创建新文件时避免意外替换。你知道吗

我的代码是检查文件名。你知道吗

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

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

有人能帮我吗?你知道吗


Tags: thetoanswerifis文件名contentsopen