gpt4 book ai didi

python - 将路径附加到路径

转载 作者:太空宇宙 更新时间:2023-11-03 16:05:37 26 4
gpt4 key购买 nike

是否可以附加一个 pathlib.Path 生成器或组合两个 Path

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返回一个生成器,即一个在调用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)

然后根据需要迭代路径,同时减少内存占用。

关于python - 将路径附加到路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com