Python脚本读取TXT文件,获取目标字符串下一行数据的问题
需求与问题
我需要编写Python脚本读取一个包含超11000行非结构化原始数据的.txt文件,要求每次匹配到指定字符串(如“SFCTEMP [K]”)时,返回其下一行的内容。现有两段尝试代码均无法实现需求:
- 第一段代码仅能返回包含目标字符串的行,无法获取下一行内容;
- 第二段代码抛出
TypeError: 'str' object is not an iterator错误,且无有效结果。
尝试的两段代码
第一段代码
file_name = input("Enter The File's Name: ") # opening and reading the file file_read = open(file_name, "r") # asking the user to enter the string to be # searched text = input("Enter the String: ") # reading file content line by line. lines = file_read.readlines() new_list = [] index = 0 # looping through each line in the file for line in lines: # if line has the input string, get the index # of that line and put the # line into newly created list if text in line: new_list.insert(index, line) index +=1 # closing file after reading file_read.close() # if length of new list is 0 that means # the input string doesn't # exist in the text file if len(new_list)==0: print("\n\"" +text+ "\" is not found in \"" +file_name+ "\"!") else: # displaying the lines # containing given string lineLen = len(new_list) print("/n**** Lines containing \"" +text+ "below / ****/n") for i in range(lineLen): print(end=new_list[i]) print()
第二段代码
# input file name with extension file = input("Enter The File's Name: ") # opening and reading the file file_read = open(file, "r") # asking the user to enter the string to be # searched text = input("Enter the String: ") for line in file_read: if text in line: print(next(line)) else: print("Text not found.")
代码问题分析
第一段代码问题
这段代码仅遍历并收集包含目标字符串的行,完全没有处理“获取匹配行下一行”的逻辑,因此无法达成需求。此外,手动管理文件关闭存在资源泄漏风险,建议使用with语句自动处理文件资源。
第二段代码问题
- 类型错误原因:
next(line)中的line是当前遍历到的字符串,而next()函数要求传入迭代器,字符串不属于迭代器类型,因此抛出TypeError。 - 逻辑错误:每次循环只要当前行不匹配就输出“Text not found”,会产生大量无效输出,且未正确处理匹配后的下一行读取逻辑。
正确实现方案
以下提供两种可行方案,均适配大文件场景,且处理了边界情况(如匹配行是文件最后一行时的提示)。
方案1:读取所有行后批量处理
适合文件大小在内存可承受范围的场景(11000行完全没问题),通过索引直接定位下一行:
file_name = input("Enter The File's Name: ") target_text = input("Enter the String: ") # 使用with语句自动关闭文件,避免资源泄漏 with open(file_name, "r") as f: lines = f.readlines() result = [] for idx, line in enumerate(lines): # 去除首尾空白后匹配,避免换行符或空格干扰 if target_text in line.strip(): # 检查下一行是否存在,防止索引越界 if idx + 1 < len(lines): result.append(lines[idx+1].strip()) else: print(f"警告:最后一行匹配到目标字符串,无下一行内容") if not result: print(f"\n\"{target_text}\" 在 \"{file_name}\" 中未找到!") else: print("\n**** 匹配行的下一行内容 ****") for content in result: print(content)
方案2:逐行迭代处理(更省内存)
无需一次性加载所有行到内存,通过迭代器特性直接读取匹配行的下一行,适合超大规模文件:
file_name = input("Enter The File's Name: ") target_text = input("Enter the String: ") result = [] with open(file_name, "r") as f: # 将文件对象转为迭代器,支持next()操作 lines_iter = iter(f) for line in lines_iter: if target_text in line.strip(): try: # 直接取下一行,迭代器会自动移动到下一个位置 next_line = next(lines_iter).strip() result.append(next_line) except StopIteration: # 捕获迭代结束异常,处理最后一行匹配的情况 print(f"警告:最后一行匹配到目标字符串,无下一行内容") if not result: print(f"\n\"{target_text}\" 在 \"{file_name}\" 中未找到!") else: print("\n**** 匹配行的下一行内容 ****") for content in result: print(content)
内容的提问来源于stack exchange,提问作者user19579091
相关产品推荐
相关产品推荐

