0

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'

oneman
  • 811
  • 1
  • 13
  • 31

1 Answers1

3

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')
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • Just one small remark: The name `content` is misleading because it will not contain the content of the file. – Matthias Jun 02 '16 at 08:16
  • @Matthias: I agree but decided to keep the variable names the same as in the question – niemmi Jun 02 '16 at 09:20