Python,传递一个包含文件名的列表以使用"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所以我现在的问题是,我不能将列表作为参数传递给函数

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

在运行函数之前,我测试了打印(a(,它给出了正确的结果,如:["00000000.txt',"0000000 1.txt",…,"00000fa7.txt"]

现在我想把00000000.txt传递给函数并做这件事,然后是00000001.txt,依此类推

请问,您能发布日志或控制台反馈吗?


分析

测试你的代码我得到

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

查看search_string__file方法,我发现的第一个">"循环在">file_name"列表上,并且每个元素都标记为">1element">

for element in file_name:

但是,您在">file_name"而不是">element"上执行"open">

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

解决方案

我认为下面报告的代码应该适用于search_string__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])

最新更新