python open() method IOError: [Errno 2] No such file or directory:

匿名 (未验证) 提交于 2019-12-03 01:52:01

问题:

For some reason, my code, that used to working, is now having trouble opening a simple .yaml file. I have tried moving around the file, giving open() the full path to the file and none of it seems to work. I saw that this question has been asked a couple times before but didnt see any answeres that solved the problem.

Any advice of how to call the file, where to move the file, or suggestions of other methods to use will be greatly appreciated!

def readYaml():     file1 = open('recentlyUpdated.yaml')     print 'opened recently updated'     companyData = yaml.load(file1)     file1.close()     print 'read recentyl updated'      file2 = open('sortedLists.yaml')     sortedLists = yaml.load(file2)     file2.close()      return companyData, sortedLists 

the error is:

file1 = open('recentlyUpdated.yaml') IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml' 

Naturally I checked that this is the correct name of the file.

回答1:

Make sure the file exists. You can then either:

  • Call os.chdir(dir), dir being the folder where the file is located, then open the file with just its name like you were doing.
  • Specify an absolute path to the file in your open call.

Remember to use a raw string if your path uses backslashes, like so: dir = r'C:\Python32'

If you went with the chdir method, you can call os.listdir() to see the list of files in the current working directory.

Let me clarify how python finds files. An absolute path is a path that starts with your computers root directory, for example 'C:\Python\scripts..' if you're on windows. A relative path is a path that does not start with your computers root directory, and is instead relative to something called the working directory. You can view python's current working directory by calling os.getcwd().

If you try to do open('sortedLists.yaml'), python will see that you are passing it a relative path, so it will search for the file inside the current working directory. Calling os.chdir will change the current working directory.

Let's say file.txt is found in `C:\Folder'.

To open it, you can do:

os.chdir(r'C:\Folder') open('file.txt') #relative path, looks inside the current working directory 

or

open(r'C:\Folder\file.txt') #full path 


回答2:

The file may be existing but may have a different path. Try writing the absolute path for the file.

Try os.listdir() function to check that atleast python sees the file.

Try it as:

file1 = open('Drive:\Dir\recentlyUpdated.yaml')



回答3:

run configuration need to be changed

change...>>> go to run configuration... go to>>> Python run see your code name you are going to run if it is wrong ,......delete that unnecessary code name....and then run it with proper arguments



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!