我遇到一个问题,当我尝试创建一个文件夹时,它会创建一个文件。具体来说,它发生在变量文件夹中。代码如下,我正在使用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
我在做什么错?我似乎无法弄清楚
答案 0 :(得分:0)
您永远不会在以下位置创建文件夹
try:
os.path.exists(folder)
except:
if not os.path.exists(folder):
print("Creating Folder for You.")
os.makedirs(folder)
如果os.path.exists
引发异常,则尝试创建文件夹,但没有,它将返回True
或False
,然后在其中创建文件>
k = open(full, "w")
那样使用
folder = raw_input("Enter Output Folder Here: ")
if not os.path.exists(folder):
print("Creating Folder for You.")
os.makedirs(folder)
答案 1 :(得分:0)
我不知道您使用此代码实现了什么,但是我对您的代码进行了一些更改。我认为这会对您有所帮助。
import os
fil = input("Enter Filename Here: ")
if not os.path.exists(fil):
print("File doesn't exist!")
folder = input("Enter Output Folder Here: ")
if not os.path.exists(folder):
print("Creating folder for you.")
os.makedirs(folder)
output = input("Enter Chlorophyll-a Output Filename Here: ")
full = os.path.join(folder, output)
if os.path.exists(full):
yesno = input("Output file already exists are you sure you want to overwrite? Yes/No: ")
if yesno == "Yes":
k = open(full, "w")
k.close()
if yesno == "No":
raise SystemExit("Exiting File Now!")
else:
print ("File Does Not Exist. I Will Make It For You.")
k = open(full, "w")
k.close()
答案 2 :(得分:0)
问题是您的代码不不存在时,您的代码未创建目录。考虑:
try:
os.path.exists(folder)
except:
if not os.path.exists(folder):
print("Creating Folder for You.")
os.makedirs(folder)
在try块中,调用os.path.exists(folder)
,但这不会产生任何异常。这意味着except子句中的代码不会执行。您想要的是创建目录,无论该目录是否存在,都可以忽略该错误:
try:
os.makedirs(folder)
except OSError:
pass