首页 > 解决方案 > 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!

标签: pythonfile

解决方案


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.


推荐阅读