python - 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()
但是,我不知道如何扫描文件夹中的文件名。
任何人都可以帮助我吗?
解决方案
您可以使用该os
库:
import os
os.path.isfile(fname)
返回True
文件的路径是否存在或者是符号链接。
推荐阅读
- mysql - MySQL查询永远执行
- android - 带有微笑的键盘和更多用户在 EditText 中使用的电话图标
- javascript - 在标准 JavaScript ES6 环境中,什么时候调用过 .toString() ?
- docker - 用于redhat基础图像的API来获取图像标签的值?
- npm - 我无法制作 package .js npm 并出现错误
- github - 克隆成功,但结帐失败
- java - SSL 异常:初始化 Alexa Skill Management API (SMAPI) 时“在握手期间收到 close_notify”
- arrays - 如何在 Julia 中索引循环数组?
- java - 模拟服务方法调用(来自内部 forEach 循环)时抛出 NullPointerException,实现此模拟的正确方法是什么?
- reactjs - ESLint:打字稿中未定义“部分”