2015-04-06 57 views
0

我有下面的代码来打印文件扩展名为* .org的文件名。我怎样才能打印找到的文件的相对路径。在此先感谢搜索带扩展名的文件名并打印其相对路径

def get_filelist() : 

directory = "\\\\networkpath\\123\\abc\\" 
filelist = [] 
for root, dirs, files in os.walk(directory): 
    for file in files: 
     if file.endswith('Org'): 
      print(str(dirs) +"\\" + str(file)) #prints empty list [] followed by filename 
      filelist.append(os.path.splitext(file)[0]) 

return (filelist) 

请把我当成新手在Python

回答

0

filesdirs列表root孩子。 dirs因此列出了file的兄弟姐妹。你想,而不是打印:

print(os.path.relpath(os.path.join(root, file))) 
+0

谢谢..但你能告诉我如何获得文件的相对路径 – Debianeese 2015-04-06 10:09:30

+0

你可以使用'os.path.relpath'来查找当前工作目录的相对路径。 https://docs.python.org/3.4/library/os.path.html?highlight=os.walk#os.path.relpath – 2015-04-06 10:15:30

0

你需要使用os.path.join

def get_filelist() : 

    directory = "\\\\networkpath\\123\\abc\\" 
    filelist = [] 
    for root, dirs, files in os.walk(directory): 
     for file in files: 
      if file.endswith('org'): # here 'org' will be in small letter 
       print(os.path.join(root,file)) 
       filelist.append(os.path.join(root,file)) 

    return filelist 
+0

dirs是一个列表,而不是一个目录 – 2015-04-06 09:58:15

+0

类型的错误,它应该是根在这里 – Hackaholic 2015-04-06 09:59:13

+0

@ThomWiggers更新帖子:) – Hackaholic 2015-04-06 10:01:03

相关问题