如何检查python中是否存在文件?
我正在尝试制作一个python脚本,以便在excel文件中创建每日条目。 我想检查文件是否存在,然后打开它。 如果文件不存在,那么我想创建一个新文件 如果已使用os路径,请查看文件是否存在如何检查python中是否存在文件?,python,excel,Python,Excel,我正在尝试制作一个python脚本,以便在excel文件中创建每日条目。 我想检查文件是否存在,然后打开它。 如果文件不存在,那么我想创建一个新文件 如果已使用os路径,请查看文件是否存在 workbook_status = os.path.exists("/log/"+workbookname+".xlxs") if workbook_status = "True": # i want to open the file Else: #i wa
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
我想你需要的就是这个
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
您应该使用以下语句:
if os.path.isfile("/{file}.{ext}".format(file=workbookname, ext=xlxs)):
# Open file
那么,当前代码中缺少的是写入现有或新文件?您当前的代码有什么问题?是的,正在写入现有文件。我想知道load_workbook()是否会覆盖现有文件,或者只是打开它,然后我可以附加到现有文件
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()