Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using os.walk to read files

I'm trying to access files rooted in subdirectories of a main directory. For this purpose, I am using os.walk(). I am able to successfully reach the file names and am able to store that in a list. However, when I try to open these files using the open(filename, 'r'), I get an error telling me that no such file or directory exits.

I think the problem here is that I am only accessing the 'names' and not the actual files itself. My code looks like this:

list_of_files = {}
for (dirpath, dirnames, filenames) in 
os.walk("C:\\Users\\Akarshkb\\Desktop\\cs361hw\\HMP_Dataset"):
    for filename in filenames:
        if filename.endswith('.txt'): 
            list_of_files[filename] = os.sep.join([dirpath, filename])
            file = open(filename, 'r')
            file.read()
            file.close()
print (list_of_files)

And I get the following error:

        `FileNotFoundError                         Traceback (most recent call 
    last)
    <ipython-input-40-10ae3e92446a> in <module>()
          4         if filename.endswith('.txt'):
          5             list_of_files[filename] = os.sep.join([dirpath, 
    filename])
    ----> 6             file = open(filename, 'r')
          7             file.read()
          8             file.close()

    FileNotFoundError: [Errno 2] No such file or directory: 'Accelerometer-2011- 
   04-11-13-28-18-brush_teeth-f1.txt'`

Any help would be much appreciated.

like image 752
Akarsh Bhagavath Avatar asked Oct 17 '22 18:10

Akarsh Bhagavath


1 Answers

You should not be ignoring the dirpath value.

Try this:

        file = open(os.path.join(dirpath, filename), 'r')
like image 103
Robᵩ Avatar answered Nov 08 '22 07:11

Robᵩ