是否可以附加一个pathlib.Path生成器或组合两个Paths?
from pathlib import Path
paths = Path('folder_with_pdfs').glob('**/*.pdf')
paths.append(Path('folder_with_xlss').glob('**/*.xls'))
通过这次尝试,您将获得:
AttributeError: 'generator' object has no attribute 'append'
是否可以附加一个pathlib.Path生成器或组合两个Paths?
from pathlib import Path
paths = Path('folder_with_pdfs').glob('**/*.pdf')
paths.append(Path('folder_with_xlss').glob('**/*.xls'))
通过这次尝试,您将获得:
AttributeError: 'generator' object has no attribute 'append'
那是因为Path.glob返回 a generator,即在next被调用时返回值的对象,它完全不知道appending 是什么。
如果您需要一个列表,则您有两个选项可以将路径包装在list调用中:
paths = list(Path('folder_with_pdfs').glob('**/*.pdf'))
paths.append(list(Path('folder_with_xlss').glob('**/*.xls')))
(尽管extend可能是您在这里所追求的。)
这当然违背了生成器的目的。
所以,我建议使用类似的东西chain并创建一个生成器,将它们组合起来并一次生成一个:
from itertools import chain
p1 = Path('folder_with_pdfs').glob('**/*.pdf')
p2 = Path('folder_with_xlss').glob('**/*.xls')
paths = chain(p1, p2)
然后根据需要进行迭代,paths同时降低内存占用。