【问题标题】:How to display filenames of word documents in a folder using python?如何使用python在文件夹中显示word文档的文件名?
【发布时间】:2020-05-30 00:54:46
【问题描述】:

我想使用python显示指定路径中存在的word文档的文件名。

【问题讨论】:

  • 使用os.listdir

标签: python arrays document docx


【解决方案1】:

@sxeros 方法的替代方法:)

import os

PATH = "your path"

files = list(filter(lambda s: ".doc" in s or ".docx" in s, os.listdir(PATH)))

print(files)

【讨论】:

    【解决方案2】:

    它可以像使用 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)
    
    

    【讨论】:

      【解决方案3】:

      这可能对你有用:

      for file in os.listdir(PATH):
          if file.endswith(".doc") or file.endswith(".docx"):
              print(file)
      

      【讨论】:

        猜你喜欢
        • 2011-06-13
        • 2010-09-20
        • 1970-01-01
        • 2012-03-04
        • 2012-03-14
        • 2015-08-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多