【问题标题】:Python script that creates new file and returns list of files创建新文件并返回文件列表的 Python 脚本
【发布时间】:2020-10-07 19:05:40
【问题描述】:

我正在尝试使用 new_directory 函数创建一个名为 script.py 的 python 脚本,该函数在当前工作目录中创建一个新目录,然后在新目录中创建一个新的空文件,并返回该目录中的文件列表. 我得到的输出是 ["script.py"] 看起来正确但给了我这个错误:

RuntimeErrorElement(RuntimeError,第 5 行错误: 目录 = os.mkdir("/home/PythonPrograms") FileExistsError:[Errno 17] 文件存在:'/home/PythonPrograms' )

import os

def new_directory(directory, filename):
  if os.path.isdir(directory) == False:
    directory = os.mkdir("/home/PythonPrograms")

  os.chdir("PythonPrograms")
  with open("script.py", "w") as file:
    pass

  # Return the list of files in the new directory
  return os.listdir("/home/PythonPrograms")

print(new_directory("PythonPrograms", "script.py"))

我该如何纠正,为什么会这样?

【问题讨论】:

  • 错误是什么?
  • 无关:不要写:if os.path.isdir(directory) == False:,请写if not os.path.isdir(directory)
  • 哦,对不起。这是我在运行脚本时遇到的错误: RuntimeErrorElement(RuntimeError,Error on line 5: directory = os.mkdir("/home/PythonPrograms") FileExistsError: [Errno 17] File exists: '/home/PythonPrograms' )跨度>

标签: python function directory


【解决方案1】:

正如其他人所说,没有错误很难调试。在正确的条件下,您的代码将不会出错。正如@Jack 所建议的那样,我怀疑您当前的目录不是/home。这意味着您在/home 目录中创建了一个名为PythonPrograms 的目录。 os.chdir("PythonPrograms") 正在尝试将目录更改为不存在的 <currentDirectory>/PythonPrograms

我已尝试将您的代码(不完全更改它)重新编写成在所有情况下都应该工作的东西。我认为这里的教训是,使用你已经拥有的变量(即directory),而不是将其硬编码到函数中。

import os

def new_directory(directory, filename):

  if not os.path.isdir(directory):
    # Create directory within current directory
    # This is working off the relative path (from your current directory)
    directory = os.mkdir(directory)

  # Create file if does not exist
  # this is a one-liner version of you with...pass statement
  open(os.path.join(directory, filename), 'a').close()

  # Return the list of files in the new directory
  return os.listdir(directory)

print(new_directory("PythonPrograms", "script.py"))

希望对你有帮助。

【讨论】:

  • 谢谢@J.Warren 从理论上讲这是有道理的。运行后出现错误: 第 17 行出错:print(new_directory("PythonPrograms", "script.py")) 第 12 行出错:open(os.path.join(directory, filename), 'a') .close()
  • 让它工作。只需要指定目录路径。再次感谢@J.Warren
【解决方案2】:

我不确定为什么你的代码中有with open("script.py", "w") as file: pass

但这是mt方式:

import os

os.mkdir('.\\Newfolder') # Create a new folder called Newfolder in the current directory
open('.\\Newfolder\\file.txt','w').close() # Create a new file called file.txt into Newfolder
print(os.listdir('.')) # Print out all the files in the current directory

【讨论】:

  • 大概这会使文件保持打开状态。使用上下文管理器语法再次关闭文件。 open('.\\Newfolder\\file.txt','w').close() 会解决这个问题
【解决方案3】:

我猜您遇到的错误是因为您无法将目录切换到PythonPrograms?这将是因为您的 python 当前工作目录不包含它。如果您更明确地写出要切换到的目录,例如输入os.chdir("/home/PythonPrograms"),那么它可能对您有用。

理想情况下,您应该向我们提供任何堆栈跟踪或有关错误的更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2020-08-04
    • 2016-08-22
    • 2011-06-02
    相关资源
    最近更新 更多