【问题标题】:How to get all type of file extensions within a directory using os.walk or glob.glob如何使用 os.walk 或 glob.glob 获取目录中所有类型的文件扩展名
【发布时间】:2019-03-14 16:39:50
【问题描述】:

我有一个代码可以检测目录中文件的语言。但是在提到扩展名的类型时,我如何检测目录中所有文件扩展名的语言(例如:- .pdf、.xlsx、.docx 等),而不仅仅是代码中提到的 .txt 文件。附上代码供参考。我想知道如何使用 glob 和 os.walk 来做到这一点。

import csv
from fnmatch import fnmatch
try:
    from langdetect import detect
except ImportError:
    detect = lambda _: '<dunno>'
import os

rootdir = '.'  # current directory
extension = '.txt'
file_pattern = '*' + extension

with open('output.csv', 'w', newline='', encoding='utf-8') as outfile:
    csvwriter = csv.writer(outfile)

    for dirpath, subdirs, filenames in os.walk(os.path.abspath(rootdir)):
        for filename in filenames:
            if fnmatch(filename, file_pattern):
                lang = detect(os.path.join(dirpath, filename))
                csvwriter.writerow([dirpath, filename, lang])

【问题讨论】:

  • 如果你的意思是你写的:“所有”文件扩展名:只需将txt 替换为*。但我_猜_你的意思是“不止一个文件扩展名,即这个列表而不是.txt only:['.pdf', '.xlsx', '.docx']”。对吗?

标签: python file-extension os.walk language-detection


【解决方案1】:

IIUC 您可以将fnmatch 支票替换为

eoi = ['*.pdf', '*.xlsx', '*.docx', '*.txt']     # extensions of interest list
if any(fnmatch(file, ext) for ext in eoi):
    lang = ... 

【讨论】:

  • 有效。谢谢你。我怎样才能避免写这部分然后 ""extension = '.txt'"" 以便它需要 .txt 以及其他文件扩展名'
  • 只要将任何文件扩展名添加到条件中的 LC 列表中即可。如果它解决了您的问题,请查看我的编辑。
  • 谢谢。另一方面,我认为代码不会读取每个文件的内容并决定语言。如何在代码中添加?
  • 我不太确定 iiuc... - 你的意思是对所需文件扩展名的过滤现在可以工作,但除此之外你对语言检测部分还有其他问题吗?
  • 好的,那么您或许应该就此提出一个新问题。我对langdetect 没有任何经验。
猜你喜欢
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 2011-03-02
  • 2021-09-18
  • 2013-05-28
  • 2019-03-07
  • 1970-01-01
  • 2022-08-24
相关资源
最近更新 更多