提问人:Bobby williams 提问时间:10/20/2023 最后编辑:phoBobby williams 更新时间:10/20/2023 访问量:29
尝试创建一个函数,该函数采用目录名和文件名,并创建目录并将文件放入其中
Trying to create a function that takes a directory name and filename and creates the directory and puts the file in it
问:
我正在 Coursera 上做一些初学者 python 课程。它给了我一个功能,让我在其中填空。我填空并得到我不理解的错误。这是带有空白的代码,因此您知道我做了什么部分。
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:
___
# Create the new file inside of the new directory
os.chdir(___)
with open (___) as file:
pass
# Return the list of files in the new directory
return ___
print(new_directory("PythonPrograms", "script.py"))
这是同样的事情,但我填补了空白。该函数应该采用目录名和文件名。然后创建并更改为该目录,并将该文件放入其中。然后返回目录和其中的文件列表。我收到一个错误,似乎与我填写的内容无关,但当然我只是一个初学者,所以我在某个地方搞砸了。
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) as file:
pass
# Return the list of files in the new directory
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))
这是我收到的错误:
Error on line 16:
print(new_directory("PythonPrograms", "script.py"))
Error on line 10:
with open (filename) as file:
FileNotFoundError: [Errno 2] No such file or directory: 'script.py'
答: 暂无答案
评论
open(filename)
filename
"script.py"