1

我有一个包含数千个文件的文件夹。我需要将每个文件的文件名与另一个数组中的列匹配。

import os

filenames = []
for files in os.walk("Directory"):
    filenames.append(files)

我现在有一个目录中每个文件名的元组。我现在想要的是拼接元组的每个元素,并将其添加到一个新数组中。我的代码与此类似:

files = []
for i in filenames:
    files.append(i[2:7])

我收到错误消息“AttributeError:'tuple' 对象没有属性'append'。” 在这里搜索后,我尝试了其他命令,例如加入。我尝试将文件名转换为列表。

即使我这样说:

filenames[0]

期望只得到第一个字符串结果,它返回整个文件名数组。有没有办法解决?

谢谢你的帮助。

4

2 回答 2

2

os.walk返回一个 3 元组:root, dirs, files

文档在这里

您可以使用列表推导来实现基于文件名的拆分。

filenames = reduce(lambda x,y: x+y, [files for root, dirs, files in os.walk('.')])
files = [name[2:7] for name in filenames]

Here are the explanations: Lambda functions are anonymous functions. You do not return anything. The definition contains expressions which are returned. This is powerful in processing dynamically generated data.

reduce() a.k.a "worker function" accepts two arguments. The function is called with first two elements of the list, then with the result of these, the third element, and so on. The return value is a single list

There are loads of documentation around this online.

于 2013-03-30T05:10:29.597 回答
1

I actually needed to include the path in the filenames and found this useful using list expressions. Since this helped me, I wanted to add the solution that gives a list with the full path:

onlyfiles = reduce(lambda x,y : x+y, [map(lambda x: root + "/" + x, files) for root, dirs, files in os.walk(mypath)])
于 2014-01-30T23:38:56.637 回答