如何检查python中是否存在文件?

新手上路,请多包涵

我正在尝试制作一个 python 脚本来在 excel 文件中创建条目,该文件将包含每日条目。我想检查文件是否存在然后打开它。如果该文件不存在,那么我想创建一个新文件。

if have used os path exists 查看文件是否存在

     workbook_status = os.path.exists("/log/"+workbookname+".xlxs")
     if  workbook_status = "True":
     # i want to open the file
     Else:
     #i want to create a new file

原文由 George Jose 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 439
2 个回答

我想你只需要那个

try:
    f = open('myfile.xlxs')
    f.close()
except FileNotFoundError:
    print('File does not exist')

如果你想检查 if-else 而不是这样做:

 from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists

原文由 Pardeep 发布,翻译遵循 CC BY-SA 4.0 许可协议

import os
import os.path

PATH='./file.txt'

if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
    print "File exists and is readable/there"
else:
    f = open('myfile.txt')
    f.close()

原文由 Stackoverflow 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题