Python无法获取文件的完整路径名 [英] Python cant get full path name of file
本文介绍了Python无法获取文件的完整路径名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试在我的驱动器上钻取一个包含子折叠的目录。当我找到我正在寻找的文件扩展名的文件时,我想要完整的文件路径。现在这是我有的:
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
返回
c:\users\name\desktop\project\file.txt
然而,file.txt位于
however that file.txt is located in
c:\users\name\desktop\project\folder1\file.txt
推荐答案
您可能需要加入文件名包含它的目录:
You probably need to join the filename with the directory that contains it:
os.path.realpath(os.path.join(root,name))
eg我刚刚测试过:
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
,并正常运作。
这篇关于Python无法获取文件的完整路径名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文