Python,传递包含文件名的列表以使用 "with open"

Python, pass a list with files names to work with "with open"

import os

counter = len(os.listdir())-1 #counts files in this directory and safes the number of files-1 (.py file) in counter var
i = 1 #used for while loop to generate the amount of elements in the list
value = 0 #starting value of the filename
a = [] #list

#loop to create the list a
while i <= counter: #starting at file one until last file (counter var)
    file = f"{value:#0{10}x}"[2:] + ".txt" #files are named hex, this converts the number in hex with 8 digits an removes the 0x th the beginning. it adds the .txt extension
    a.append(file) #saves the filename in the list of a
    i += 1
    value += 1

b = input("Enter keyword: ")

"""function takes file_name from a (list) and string_to_search b
opens file, search for the word and prints a string from start of the word to the next period (.)"""

def search_string_in_file(file_name, string_to_search):
    for element in file_name:
        results = ""
        with open(file_name, 'r' , encoding='latin1') as read_obj:
            for line in read_obj:
                word_index = line.find(string_to_search)
                if (word_index != -1):
                    period_index = line.find('.', word_index+len(string_to_search))
                    print(line[word_index:period_index+1])

search_string_in_file(a, b)

文件名为“8 位十六进制 (0-f) 小写”.txt 所以我现在的问题是,我无法将列表作为参数传递给函数

我想要在所有文件中搜索该特定单词并打印从该单词开始到下一个句点的句子

我在 运行 函数之前测试了 print(a),它给出了正确的结果,例如: ['00000000.txt', '00000001.txt', ..., '00000fa7.txt']

现在我想将 00000000.txt 传递给函数并执行操作,然后 00000001.txt 依此类推

拜托,你能post日志或控制台反馈吗?


分析

正在测试我得到的代码

TypeError: expected str, bytes or os.PathLike object, not list

查看 search_string_in_file 方法,我看到第一个 'for' 循环在 'file_name' 列表,每个元素都标记为 'element'

for element in file_name:

但是您在“file_name”而不是“元素

with open(file_name, 'r' , encoding='latin1') as read_obj:

解决方案

我认为下面报告的代码应该适用于 search_string_in_file 函数:

def search_string_in_file(file_name, string_to_search):
    for element in file_name:
        results = ""
        with open(element, 'r' , encoding='latin1') as read_obj:
            for line in read_obj:
                word_index = line.find(string_to_search)
                if (word_index != -1):
                    period_index = line.find('.', word_index+len(string_to_search))
                    print(line[word_index:period_index+1])