Liam Emery Liam Emery - 8 months ago 36
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")

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


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')