13

Trying to drill through a directory on my drive that has subfoldrs within it. When I find files that have the file extensions I'm looking for I want the full file path. Right now this is what I have:

import os
import Tkinter
import tkFileDialog
from Tkinter import Tk
from tkFileDialog import askopenfilename

root = Tkinter.Tk().withdraw()
dirname = tkFileDialog.askdirectory(initialdir='.')

list = [] 


for root, dirs, files in os.walk(dirname):
    for name in files:
        if name.find(".txt") != -1:
           name = str(name)
           name = os.path.realpath(name)
           list.append(name)

print list

This is returned

c:\users\name\desktop\project\file.txt

however that file.txt is located in

c:\users\name\desktop\project\folder1\file.txt
shreddish
  • 1,637
  • 8
  • 24
  • 38

2 Answers2

9

You probably need to join the filename with the directory that contains it:

os.path.realpath(os.path.join(root,name))

e.g. I just tested this:

import os
for root, dirs, files in os.walk('.'):
    for name in files:
        if name == 'foo':
           name = str(name)
           name = os.path.realpath(os.path.join(root,name))
           print name

with the following directory structure:

test
  + foo
  + test2
     + foo

and it worked properly.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    worked perfectly thank you! not sure why I was receiving down votes on this when the other question that was already asked didnt even answer my own question... – shreddish Jul 18 '13 at 17:48
  • @reddman -- FWIW, I didn't understand the downvotes either. I upvoted. :) – mgilson Jul 18 '13 at 17:51
0

Use:

os.path.abspath

instead. Your path is not absolute.

Ali Afshar
  • 40,967
  • 12
  • 95
  • 109
  • agreed, I was using os.path.abspath(file) and it was missing the parent folder in the returned filepath. – agleno Jul 05 '18 at 11:41