Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory

前端 未结 5 1291
孤街浪徒
孤街浪徒 2020-11-22 06:24

For some reason my code is having trouble opening a simple file:

This is the code:

file1 = open(\'recentlyUpdated.yaml\')

And the erro

5条回答
  •  抹茶落季
    2020-11-22 07:12

    Most likely, the problem is that you're using a relative file path to open the file, but the current working directory isn't set to what you think it is.

    It's a common misconception that relative paths are relative to the location of the python script, but this is untrue. Relative file paths are always relative to the current working directory, and the current working directory doesn't have to be the location of your python script.

    You have three options:

    • Use an absolute path to open the file:

      file = open(r'C:\path\to\your\file.yaml')
      
    • Generate the path to the file relative to your python script:

      from pathlib import Path
      
      script_location = Path(__file__).absolute().parent
      file_location = script_location / 'file.yaml'
      file = file_location.open()
      

      (See also: How do I get the path and name of the file that is currently executing?)

    • Change the current working directory before opening the file:

      import os
      
      os.chdir(r'C:\path\to\your\file')
      file = open('file.yaml')
      

    Other common mistakes that could cause a "file not found" error include:

    • Accidentally using escape sequences in a file path:

      path = 'C:\Users\newton\file.yaml'
      # Incorrect! The '\n' in 'Users\newton' is a line break character!
      

      To avoid making this mistake, remember to use raw string literals for file paths:

      path = r'C:\Users\newton\file.yaml'
      # Correct!
      

      (See also: Windows path in Python)

    • Forgetting that Windows doesn't display file extensions:

      Since Windows doesn't display known file extensions, sometimes when you think your file is named file.yaml, it's actually named file.yaml.yaml. Double-check your file's extension.

提交回复
热议问题