2013-07-18 90 views
9

試圖鑽取我的驅動器中具有子摺疊器的目錄。當我找到具有我正在查找的文件擴展名的文件時,我需要完整的文件路徑。現在,這是我有:Python無法獲得文件的完整路徑名稱

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 

這是返回

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

但是該file.txt的位於

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

回答

8

您可能需要使用包含它的目錄中加入文件名:

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

例如我只是測試這一點:

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 

具有以下目錄結構:

test 
    + foo 
    + test2 
    + foo 

和它的工作正常。

+1

完美謝謝你!不知道爲什麼我在這個問題上接受了投票,當時已經問過的另一個問題甚至沒有回答我自己的問題... – shreddish

+0

@reddman - FWIW,我也不明白downvotes。我upvoted。 :) – mgilson

+0

哈哈再次感謝你 – shreddish

0

用途:

os.path.abspath 

代替。你的道路不是絕對的。

+0

我已經試過abspath它返回相同的結果 – shreddish