Python os.walk总是附加root

时间:2015-12-22 11:17:27

标签: python root os.walk

对于我的学习,我正忙着用Python开发一个项目。

我对一些非常奇怪的东西感到困惑。

这是我正在运行的代码(代码的一小部分,但它也会产生相同的错误):

import os

path_input = raw_input('Give path to check for documents(e.g. /Users/Frank/Desktop): ')
if os.path.isdir(path_input):
    for root, dirs, files in os.walk(path_input):
        for file in dirs:
            if os.path.splitext(file)[1].lower() in ('.docx', '.pdf', '.doc', '.pptx', '.txt',
                '.ppt', 'xls', 'xlsx'):
                print(os.path.abspath(file))
else:
    print("\nPlease enter a valid path, for example: '/Users/Frank/Documents.'")

它读取它遇到的任何文件,它在os.walk中找到,但每当print(os.path.abspath(file))部分到来时,它总是附加我存储脚本的根文件夹。

我似乎无法找出我做错了什么。

更新(添加输出示例):

/Users/Username/Dropbox/Test/Python/version5.txt
/Users/Username/Dropbox/Test/Python/version6.txt
/Users/Username/Dropbox/Test/Python/version7.txt

如你所见,它总是说“/ Users / Username / Dropbox / Test / Python /” 当.txt文件存储在另一个位置时,它与存储的python脚本的位置相同。

2 个答案:

答案 0 :(得分:2)

每当您致电os.walk时,都会返回 root 目录列表以及文件列表。虽然你的程序看起来像是正确的英语,但它并不是你想要用Python做的。第for file in dirs查看目录中的所有文件;它只是循环遍历root的所有子文件夹。我认为你真正想要的是转而使用files

import os

path_input = raw_input('Give path to check for documents(e.g. /Users/Frank/Desktop): ')
if os.path.isdir(path_input):
    for root, dirs, files in os.walk(path_input):
        ### iterate over files instead of dirs
        for file in files:
            # The full file path needs to be made by joining with root.
            fullfile = os.path.join(root, file)
            if os.path.splitext(fullfile)[1].lower() in ('.docx', '.pdf', '.doc', '.pptx', '.txt',
                '.ppt', 'xls', 'xlsx'):
                print(os.path.abspath(fullfile))
else:
    print("\nPlease enter a valid path, for example: '/Users/Frank/Documents.'")

答案 1 :(得分:2)

您可以使用str.endswith查找匹配的文件,还需要搜索非dirs的文件并加入根目录:

import os

ends = ('.docx', '.pdf', '.doc', '.pptx', '.txt','.ppt', 'xls', 'xlsx')
path_input =  raw_input('Give path to check for documents(e.g. /Users/Frank/Desktop): ')
if os.path.isdir(path_input):
     files = (os.path.abspath(f) for root, dirs, files in os.walk(path_input)
              for f in files if f.endswith(ends))
    for f in files:
        print(f)
else:
    print("\nPlease enter a valid path, for example: '/Users/Frank/Documents.'")