我正在尝试制作一个 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
Run Code Online (Sandbox Code Playgroud)
我想你只需要那个
try:
f = open('myfile.xlxs')
f.close()
except FileNotFoundError:
print('File does not exist')
Run Code Online (Sandbox Code Playgroud)
如果你想检查 if-else 而不是这样做:
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
Run Code Online (Sandbox Code Playgroud)