【发布时间】:2020-05-30 00:54:46
【问题描述】:
我想使用python显示指定路径中存在的word文档的文件名。
【问题讨论】:
-
使用
os.listdir
标签: python arrays document docx
我想使用python显示指定路径中存在的word文档的文件名。
【问题讨论】:
os.listdir
标签: python arrays document docx
@sxeros 方法的替代方法:)
import os
PATH = "your path"
files = list(filter(lambda s: ".doc" in s or ".docx" in s, os.listdir(PATH)))
print(files)
【讨论】:
它可以像使用 scandir 传递文件扩展名创建自定义迭代器一样简单(对于 Word 文档,您可以使用 docx)。像这样:
import os
from typing import Type, Iterable
def scan_dir(path, file_ext) -> Iterable[Type[os.DirEntry]]:
for dir_entry in os.scandir(path):
if dir_entry.name.endswith(f'.{file_ext}'): yield dir_entry
if __name__ == '__main__':
for word_doc in scan_dir('.', 'docx'):
print(word_doc.name)
【讨论】:
这可能对你有用:
for file in os.listdir(PATH):
if file.endswith(".doc") or file.endswith(".docx"):
print(file)
【讨论】: