【问题标题】:Search for a specific word in multiple csv files在多个 csv 文件中搜索特定单词
【发布时间】:2021-04-01 13:27:52
【问题描述】:

我是 python 新手,手头有一个任务。我在一个文件夹中有多个 csv 文件,需要在这些文件中找到一个特定的单词。然后我需要文件名。有没有python的程序员可以给我一些指导?

【问题讨论】:

  • 您能否向我们展示您到目前为止所做的尝试?

标签: python string csv search


【解决方案1】:

也许是这样的:

from glob import glob
text = 'test'
for filename in glob('*.csv'):
    with open(filename) as input_file:
        if text in input_file.read():
            print(f'{text} was found in file {filename}')

编辑:将其移至函数中 ->

from glob import glob


def find_files_with_text(pathname, value):
    files_containing_value = []
    for filename in glob(pathname):
        with open(filename) as input_file:
            if value in input_file.read():
                files_containing_value.append(filename)
    return files_containing_value


path = './*.txt'
text = 'test'

print(find_files_with_text(path, text))

【讨论】:

  • 这将根据用户的问题起作用。甚至可以用于创建函数,并在找到 text 时从循环内返回 filename
  • @LiamFiddler 的代码是什么?
  • 另外,有什么方法可以让它解析一个包含 csv 文件的文件夹,而不是一次解析一个 csv 文件?
  • 我已经编辑了我的答案并添加了一个功能。我不确定您如何设想一种避免逐个打开单个文件的解决方案。您是否正在考虑并行运行的线程?分布式文件系统,如 hdfs,可能对此有用(?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
相关资源
最近更新 更多