【发布时间】:2019-11-24 06:21:16
【问题描述】:
我遇到了一个问题,当我尝试创建一个文件夹时,它会创建一个文件。具体来说,它出现在变量文件夹中。代码如下,我使用的是python 2.7
import os
i = False
while i != True:
fil = raw_input("Enter Filename Here: ")
i = os.path.exists(fil)
if i == False: print("File does not exist! Try Again.")
folder = raw_input("Enter Output Folder Here: ")
try:
os.path.exists(folder)
except:
if not os.path.exists(folder):
print("Creating Folder for You.")
os.makedirs(folder)
output = raw_input("Enter Chlorophyll-a Output Filename Here: ")
full = os.path.join(folder, output)
if os.path.exists(full):
yesno = raw_input("Output file already exists are you sure you want to overwrite? Yes/No: ")
if yesno == "Yes":
k = open(full, "w")
if yesno == "No":
raise SystemExit("Exiting File Now!")
if not os.path.exists(full):
print ("File Does Not Exist. I Will Make It For You.")
k = open(full, "w")
在我的电脑上出现此错误
Traceback (most recent call last):
File "C:/Users/---/.PyCharmCE2019.2/config/scratches/scratch_6.py", line 33, in <module>
k = open(full, "w")
IOError: [Errno 2] No such file or directory
我做错了什么?我似乎无法弄清楚
【问题讨论】:
-
“它会生成文件”是什么意思? os.makedirs 无法创建文件。它是在制作一个具有文件扩展名的文件夹吗?
-
由于某种原因,当我运行此代码时,它根本没有创建文件夹,而只是一个绝对不是文件夹目录的空文件。它根本不会创建一个全新的文件夹,只是一个空文件。
-
你在运行脚本时输入了什么路径?
-
我的输入只是一个 excel xlsm 文件 C:/Users/---/documents/excelfile.xlsx。对于我的输出文件夹,我做了 C:/Users/---/Desktop/output。其中输出是一个不存在的文件夹,我想创建一个。
-
您似乎误解了 os.path.exists 的工作原理。它返回 True 或 False 取决于你给它的路径是否已经存在。它不会抛出异常,因此您创建文件夹的 except: 子句永远不会实际执行。