Liam Emery Liam Emery - 6 months ago 23
Python Question

How do I open all files in a directory in python?

I have the code

import os

def Load():
for filename in os.listdir("directoryPath"):
content = open(filename, "r")
Load()


And I would like to know how to load the files that
filename
returns, at the moment I just get an error saying
FileNotFoundError: [Errno 2] No such file or directory: 'Adjectives.txt'

Answer

os.listdir() returns only the filename, not the full path. You need to pass the whole path to open. You can use os.path.join to combine directory and filename:

content = open(os.path.join('directoryPath', filename), 'r')