1

I am trying read my python files in a directory. I am getting an error

Traceback (most recent call last):
  File "/home/akallararajappan/codes to handle unicode/read_directory.py", line 42, in <module>
    open_file( filename)
  File "/home/akallararajappan/codes to handle unicode/read_directory.py", line 31, in open_file
    data = open (fil_name, 'r').read()
IOError: [Errno 2] No such file or directory: 'createFile.py' 

This is my code :

import os
import codecs
def open_file(fil_name) :
    data = open (fil_name, 'r').read()
    print data 



for dirname, dirnames, filenames in os.walk('/home/akallararajappan/corpus'):
    print()
    #print(dirname + ":")
    for filename in filenames:
        open_file( filename)

What is the problem here?

1 Answers1

5

The filenames in os.walk() do not have a full path; they are always relative to dirname. Add the dirname path first before trying to open the file:

for dirname, dirnames, filenames in os.walk('/home/akallararajappan/corpus'):
    for filename in filenames:
        open_file(os.path.join(dirname, filename))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343