Python open() gives "FileNotFoundError: [Errno 2] No such file or directory:", but the file exists

Viewed 3440

I'm trying to read all the files in a directory and append the text in them into a list but I get the error in the header. However, the file actually exists. My code is:

pos_lines = []
train_pos_path = r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'
# print(os.listdir(train_pos_path))
for filename in os.listdir(train_pos_path):
    with open(filename, "r",encoding="utf-8", errors='ignore') as f:
        for line in f.readlines():
            pos_lines.append(line)

The path is the absolute path of the directory and print(os.listdir(train_pos_path)) gives the list of the files under that directory. However, I can't open the files in it and it gives me the error I mentioned. My code I'm trying to run is in "C:\Users\Halid\Desktop\nlp_p5". Does anybody know why I'm getting this error and how can I solve this?

1 Answers

You've specified an absolute path to the directory, r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'. You then proceeded to list all files with their filenames, receiving A, B, C, ...

However, A, B, C, ... are not located in the directory you're running your python script. Try calling

os.chdir(train_pos_path)

before calling the for loop.

Another solution would be to prepend each path with train_pos_path:

train_pos_path = r'C:\Users\Halid\Desktop\nlp_p5\nlp_dir2\TRAIN\posTr'

for filename in os.listdir(train_pos_path):
    with open(os.path.join(train_pos_path, filename), "r",encoding="utf-8", errors='ignore') as f:
        for line in f.readlines():
            pos_lines.append(line)

The key takeaway from this is the fact that os.listdir(directory) returns just the names as seen from the directory, not their absolute paths.

Related