Python代码问题:Header无法迭代,始终输出同一内容
问题描述
当前代码每次触发打印Header时,只会输出header_file中的第一行内容,需要改成每次触发时按顺序输出下一行Header。
原有代码
def PhaseInterval(arrival_file, filter_file, header_file): # read the stations from the filter file with open(filter_file, 'r') as f: filter_stations = [line.strip() for line in f.readlines()] # read the new header from the header file with open(header_file, 'r') as f: new_header = f.readline().strip() with open(arrival_file, 'r') as f: data = f.readlines() for i, line in enumerate(data): if 'pha' in line and len(line.split()) > 8: station = line.split()[0] print(new_header) #print(station, line.split()[4], line.split()[5], line.split()[7]) elif 'amp' not in line and len(line.split()) > 8 and 'Origin' not in line: station = line.split()[0] if station in filter_stations: print(station, line.split()[4], line.split()[5], line.split()[8]) PhaseInterval('garut_arrivals.txt','name_of_station','event_format.csv')
当前运行结果
2018 1 15 19 40 39.8 -7.41306 107.71983 10.0 2.7 0.0 0.0 0.82 1 BBJI P 19:40:43.1 1.0 BBJI S 19:40:45.6 1.0 CNJI P 19:40:51.5 1.0 CNJI S 19:41:00.0 1.0 LEM P 19:40:51.3 1.0 LEM S 19:40:59.8 1.0 2018 1 15 19 40 39.8 -7.41306 107.71983 10.0 2.7 0.0 0.0 0.82 1 BBJI Pg 15:20:57.8 1.0 LEM P 15:21:01.0 1.0 CNJI P 15:21:03.6 1.0 JCJI P 15:21:05.5 1.0 2018 1 15 19 40 39.8 -7.41306 107.71983 10.0 2.7 0.0 0.0 0.82 1 BBJI P 22:33:45.9 1.0 BBJI S 22:33:49.9 1.0 LEM P 22:33:49.0 1.0 ...
header_file内容
2018 1 15 19 40 39.8 -7.41306 107.71983 10.0 2.7 0.0 0.0 0.82 1 2018 2 5 15 20 51.9 -7.21515 107.71812 12.0 2.7 0.0 0.0 0.65 2 2018 2 17 22 33 40.4 -7.25412 107.71104 10.0 2.9 0.0 0.0 0.53 3 2018 4 10 13 46 9.9 -7.23121 107.67741 10.0 2.4 0.0 0.0 0.64 4 2018 4 30 17 25 58.9 -7.18669 107.61525 10.0 2.4 0.0 0.0 0.68 5 2018 5 15 21 5 55.9 -7.20198 107.63742 10.0 1.8 0.0 0.0 0.47 6 ...
解决方案
问题根源是只读取了header_file的第一行,且没有跟踪当前应输出的Header位置。修改思路是把所有Header存入列表,用计数器控制每次触发时取列表的下一个元素。
修改后的代码:
def PhaseInterval(arrival_file, filter_file, header_file): # 读取过滤站点列表 with open(filter_file, 'r') as f: filter_stations = [line.strip() for line in f.readlines()] # 读取所有Header到列表,过滤空行 with open(header_file, 'r') as f: headers = [line.strip() for line in f if line.strip()] header_index = 0 # 初始化Header索引 with open(arrival_file, 'r') as f: data = f.readlines() for line in data: if 'pha' in line and len(line.split()) > 8: # 检查是否还有未使用的Header if header_index < len(headers): print(headers[header_index]) header_index += 1 # 可选:Header用完后的兜底逻辑,比如循环使用第一个Header # else: # print(headers[0]) elif 'amp' not in line and len(line.split()) > 8 and 'Origin' not in line: station = line.split()[0] if station in filter_stations: print(station, line.split()[4], line.split()[5], line.split()[8]) PhaseInterval('garut_arrivals.txt','name_of_station','event_format.csv')
修改说明
- 一次性读取
header_file所有有效行到headers列表,避免重复打开文件。 - 用
header_index变量跟踪当前要输出的Header位置,每次触发后自增。 - 添加索引越界检查,防止Header用完后报错,可根据需求补充兜底逻辑。
内容的提问来源于stack exchange,提问作者Boy Immanuel
相关产品推荐
相关产品推荐

