找不到文件目录错误。请帮助。FileNotFoundError:[Errno 2]没有这样的文件或目录:';script.py'; 导入操作系统 def新目录(目录,文件名): #在创建新目录之前,请检查它是否已经存在 如果os.path.isdir(目录,mode=“w+”)==False: os.mkdir(目录) #在新目录中创建新文件 chdir(目录) 打开(文件名)作为文件: 通过 #返回新目录中的文件列表 返回os.listdir(目录) 打印(新目录(“PythonPrograms”、“script.py”))
我的代码显示此错误:找不到文件目录错误。请帮助。FileNotFoundError:[Errno 2]没有这样的文件或目录:';script.py'; 导入操作系统 def新目录(目录,文件名): #在创建新目录之前,请检查它是否已经存在 如果os.path.isdir(目录,mode=“w+”)==False: os.mkdir(目录) #在新目录中创建新文件 chdir(目录) 打开(文件名)作为文件: 通过 #返回新目录中的文件列表 返回os.listdir(目录) 打印(新目录(“PythonPrograms”、“script.py”)),python,mkdir,Python,Mkdir,我的代码显示此错误: Traceback (most recent call last): File "C:\Users\Toshiba\Desktop\new.py", line 16, in <module> print(new_directory("PythonPrograms", "script.py")) File "C:\Users\Toshiba\Desktop
Traceback (most recent call last):
File "C:\Users\Toshiba\Desktop\new.py", line 16, in <module>
print(new_directory("PythonPrograms", "script.py"))
File "C:\Users\Toshiba\Desktop\new.py", line 14, in new_directory
return os.listdir(directory)
FileNotFoundError: [WinError 3] The system cannot find the path specified:
'PythonPrograms'
[Finished in 0.1s]
回溯(最近一次呼叫最后一次):
文件“C:\Users\Toshiba\Desktop\new.py”,第16行,在
打印(新目录(“PythonPrograms”、“script.py”))
文件“C:\Users\Toshiba\Desktop\new.py”,第14行,在新目录中
返回os.listdir(目录)
FileNotFoundError:[WinError 3]系统找不到指定的路径:
“蟒蛇程序”
[在0.1s内完成]
我尝试了不使用mode=“w+”的方法,然后又出现了一个错误。您的
打开功能中缺少该模式
import os
def new_directory(directory, filename):
# Before creating a new directory, check to see if it already exists
if os.path.isdir(directory) == False:
os.mkdir(directory)
# Create the new file inside of the new directory
os.chdir(directory)
with open(filename, mode="w+") as file:
pass
# Return the list of files in the new directory
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))
os.listdir(目录)
从父目录中查找目录“directory”。它不列出当前目录。因此,删除行os.chdir(目录)
但这是另一个错误。。。如果需要帮助,您应该尝试查找它,或者至少提供错误的回溯。
import os
def new_directory(directory, filename):
# Before creating a new directory, check to see if it already exists
if os.path.isdir(directory) == False:
os.mkdir(directory)
# Create the new file inside of the new directory
with open(filename, mode="w+") as file:
pass
# Return the list of files in the new directory
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))