【问题标题】:file directory not found error.Please help.FileNotFoundError: [Errno 2] No such file or directory: 'script.py'找不到文件目录错误。请帮助。FileNotFoundError:[Errno 2] 没有这样的文件或目录:'script.py'
【发布时间】:2020-06-30 15:04:07
【问题描述】:
import os

def new_directory(directory, filename):
    # Before creating a new directory, check to see if it already exists
    if os.path.isdir(directory,mode="w+") == 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"))

我的代码显示此错误:

     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]

我试过不使用 mode="w+" 然后我得到另一个错误..

【问题讨论】:

    标签: python mkdir


    【解决方案1】:

    os.listdir(directory) 从其父目录中查找目录“目录”。它没有列出 当前 目录。因此删除os.chdir(directory)这一行。

    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"))
    

    【讨论】:

      【解决方案2】:

      您在 open 函数中缺少模式

      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"))
      

      【讨论】:

      • 但这是另一个错误...如果需要帮助,您应该尝试查找它或至少提供错误的回溯。
      猜你喜欢
      • 2021-08-26
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多