1

I am writing a program to read a set of text files from folder "set" to a list.My code for this is

def get_documents():
    path1 = "D:/set/"
    texts = []
    listing1 = os.listdir(path1)
    for file in listing1:
        with open(file,'r') as f:
            lines = f.read().splitlines()
            texts.append(lines)

But this gives me Error as

with open(file,'r') as f:
IOError: [Errno 2] No such file or directory: '0.txt'

There are text files inside D:/set/ namely 0.txt,1.txt,2.txt... What is the reason for this Error?

Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38
Emmanu
  • 749
  • 3
  • 10
  • 26

1 Answers1

2

The function os.listdir() returns the file names in the directory and not the full path which is expected by open().

You can solve it by joining the base path to the file name.

with open(os.path.join(path1, file),'r') as f:
    ...

Another alternative is to use glob() to avoid paths joining:

import glob
path1 = "D:/set/*"
listing1 = glob.glob(path1)
for file in listing1:
    with open(file,'r') as f:
        ...
Elisha
  • 23,310
  • 6
  • 60
  • 75