使用Python的文件和目录

问题描述 投票:0回答:1

我正在做一个练习问题,我必须创建自己的目录并使用Python将文件放入其中,但始终出现错误。我可以在下面发布我的代码和错误消息。

代码:

import os

def new_directory(directory, filename):
  # Before creating a new directory, check to see if it already exists
  if not os.path.exists(directory):
    os.mkdir(directory)

  # Create the new file inside of the new directory
  os.chdir(directory)
  with open(filename, "w") 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 14:
    return os.listdir(directory)
FileNotFoundError: [Errno 2] No such file or directory: 'PythonPrograms'
python file-io
1个回答
0
投票
os.chdir(directory)

此行将您放入刚刚创建的目录中。稍后尝试引用该文件夹时,因为位于其中,所以看不到它。

最简单的解决方法是在添加文件后备份目录:与

open(filename, "w") as file:
    pass

os.chdir("..")  # Go back up to the parent

return os.listdir(directory)
© www.soinside.com 2019 - 2024. All rights reserved.