使用os.walk查找文件路径

1 投票
2 回答
3671 浏览
提问于 2025-04-17 20:32

我在我的笔记本电脑上保存了一些文件。文件夹的结构是这样的:

Part1(folder)
 Part1(subfolder)
  awards_1990 (subfolder)
     awards_1990_00 (subfolder)
        (files)
     awards_1990_01
        (files)
        ...
        ...
        ...
  awards_1991
    awards_1991_01
      (files)
    awards_1991_01
    awards_1991_01
     ...
     ...
     ...
  awards_1992
     ...
     ...
     ...
  awards_1993
     ...
     ...
     ...
  awards_1994
     ...
     ...
     ...

所以我想用os.walk来提取文件路径的列表。我写的代码是这样的:

import os
matches=[]
for root, dirnames, dirname in os.walk('E:\\Grad\\LIS\\LIS590 Text mining\\Part1\\Part1'):
    for dirname in dirnames:
        for filename in dirname:
                if filename.endswith(('.txt','.html','.pdf')):
            matches.append(os.path.join(root,filename))

当我调用matches时,它返回的是[]。

我试了另一段代码:

import os
dirnames=os.listdir('E:\\Grad\\LIS\\LIS590 Text mining\\Part1\\Part1')
for filenames in dirnames:
    for filename in filenames:
        path=os.path.join(filename)
        print (os.path.abspath(path))

这段代码给我的结果是:

C:\Python32\a
C:\Python32\w
C:\Python32\a
C:\Python32\r
C:\Python32\d
C:\Python32\s
C:\Python32\_
C:\Python32\1
...

我在研究这个错误。有没有什么建议可以解决这个问题?

2 个回答

3

函数 endswith 的参数是:suffix[, start[, end]]。这意味着如果你有多个后缀的话,就需要把它们放在括号里:

if filename.endswith(('.txt','.html','.pdf')):
1

for filename in dirname: 这段代码是用来一个一个地读取 dirname 这个字符串里的每个 字符。你可以试试看:

#!/usr/bin/env python
import os

topdir = r'E:\Grad\LIS\LIS590 Text mining\Part1\Part1'
matches = []
for root, dirnames, filenames in os.walk(topdir):
    for filename in filenames:
        if filename.endswith(('.txt','.html','.pdf')):
            matches.append(os.path.join(root, filename))
print("\n".join(matches))

在这里,你不需要用 for 循环来处理 dirnames

撰写回答