【问题标题】:Python cant get full path name of filePython无法获取文件的完整路径名
【发布时间】:2013-07-17 19:11:30
【问题描述】:

试图钻取驱动器上包含子文件夹的目录。当我找到具有我正在寻找的文件扩展名的文件时,我想要完整的文件路径。现在这就是我所拥有的:

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

【问题讨论】:

    标签: python path directory


    【解决方案1】:

    用途:

    os.path.abspath
    

    相反。你的路径不是绝对的。

    【讨论】:

    • 同意,我使用的是 os.path.abspath(file),但返回的文件路径中缺少父文件夹。
    【解决方案2】:

    您可能需要将文件名与包含它的目录连接起来:

    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
    

    它工作正常。

    【讨论】:

    • 工作得很好,谢谢!不知道为什么当已经提出的另一个问题甚至没有回答我自己的问题时,我对此投了反对票......
    • @reddman -- FWIW,我也不明白反对意见。我投了赞成票。 :)
    猜你喜欢
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多