Harmless
Harmless

Reputation: 11

Using os.walk to find and print names of my files, but unable to open them? Path name issue?

My relevant code block is as follows:

path = "\\Users\\Harmless\\Documents\\untitled"
cellorder = []
cellcont = []
for roots, dirs, files, in os.walk(path):
    for file in natural_sort(files):
        if "Row" in file:
            cellorder.append(file)
            with open(file,'r') as txt:
                print txt.readlines
            #print "file = %s" % file

This would successfully list all the files I want to open (as commented out), but when I try to pass in the filename the same way it was printed in order to read it:

IOError: [Errno 2] No such file or directory: 'Row0Col0Heat.txt'

How can I fix this? Do I need to reference the entire path name and string substitute in each filename? If so, why? Is there a better way to reference/utilize paths?

Upvotes: 0

Views: 899

Answers (1)

Bubble Bubble Bubble Gut
Bubble Bubble Bubble Gut

Reputation: 3358

Try using the absolute path of the file, you can get the absolute path by

abs_file_path = os.path.abspath(file)

since you already have the base path, you can also use:

abs_file_path = os.path.join(path, file)

Hope it helps

Upvotes: 1

Related Questions