Liam Emery Liam Emery - 1 year ago 104
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'

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download