首页 > 解决方案 > 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()

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

任何人都可以帮助我吗?

标签: pythonfile

解决方案


您可以使用该os库:

import os
os.path.isfile(fname)

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


推荐阅读