Using os.walk to read files [duplicate]
Asked Answered
P

1

6

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.

Pridgen answered 8/5, 2018 at 18:21 Comment(1)
os.path.join(dirpath, filename) or for Python 3.4+ pathlib.Path(dirpath, filename)Recondition
D
5

You should not be ignoring the dirpath value.

Try this:

        file = open(os.path.join(dirpath, filename), 'r')
Doug answered 8/5, 2018 at 18:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.