python - FileNotFoundError: [Errno 2] No such file or directory althoguh the file exists
问题描述
I am iterating over a directory, which contains some files.
I want to get the content out of the files. But I receive all the time the error message:
FileNotFoundError: [Errno 2] No such file or directory: 'artikel1.txt'
It even mentions the name of the file! (artikel1.txt).
Here my code:
import os
entries = os.listdir(POSITIVEFILES_PATH)
for file in entries:
text_file = open(file,"r")
print(text_file.read())
Why do I get this error message? The files are in a relative path directory. Before I received some messages, that I do not have the permission for whatever
Please help!
解决方案
That's becauseos.listdir
only give you a list of the file names not their full paths, if you are lucky enough and the files are in the same directory as your program file then it will raise no error.
For example I had a program file in my projects
directory and I ran it with os.istdir('../')
, that would return only the names of the files at the outer/containing folder like this
['file1', 'file2',]
so I have to open the like this
open('../' + 'file1', 'r')
In Normal case you would do something like this to make sure that you always giving the open function a fully described path
open(POSITIVEFILES_PATH + file, "r")
also you could find os.path.join
more useful and neat in doing such joins of paths.
推荐阅读
- azure-data-factory-2 - 如何从 ADFV2 中的 if 活动引发错误?
- react-native - React native Alert 可以等待用户响应吗?
- c++ - 在'minflightNumber'和'maxflightNumber'之前不断获得预期的主要表达式......不知道该怎么做
- deployment - Microsoft Click-Once 和混淆 DLL
- python - 正则表达式列表
- scala - Scala 将函数序列作为参数类型传递
- python - 登陆页面未加载 - Selenium Web 表单自动化
- ios - 无法让 AVPortraitEffectsMatte 代码工作
- matlab - matlab中的三相图?
- validation - Spring 2 + Thymeleaf + 验证 = Whitelabel 错误页面 500