Python文件操作:添加指定城市数据与计算学校代码得票总和
问题背景
我有一个包含不同城市学校代码及得票数据的文件,格式示例如下:
City: California ADS, 532 SJD, 221 WPE, 239 City: Chicago ADS, 238 SJD, 233 WPE, 456 ...
作为Python初学者,尝试用字典处理时感到困惑,提出以下两个技术问题:
- 如何向文件中指定城市(如Chicago)的分类下添加数据(如DJF, 204),而非直接追加到文件末尾?
- 如何计算各学校代码(如WPE)在所有城市中的总得票数?
问题解答
1. 向指定城市分类下添加数据
文本文件无法直接在中间插入内容,得先把整个文件读到内存里,找到目标城市对应的位置,插入新数据后再写回文件。具体实现如下:
def add_school_to_city(file_path, target_city, school_data): # 读取文件所有行,保留原换行符 with open(file_path, 'r') as f: lines = f.readlines() target_city_line = f"City: {target_city}\n" insert_pos = None # 定位目标城市的位置,并确定插入点 for idx, line in enumerate(lines): if line == target_city_line: # 从目标城市行的下一行开始,找下一个City:标记 insert_pos = idx + 1 for next_idx in range(idx + 1, len(lines)): if lines[next_idx].startswith("City: "): insert_pos = next_idx break break if insert_pos is not None: # 插入新数据(记得加换行符) lines.insert(insert_pos, f"{school_data}\n") # 将修改后的内容写回文件 with open(file_path, 'w') as f: f.writelines(lines) else: print(f"未找到目标城市:{target_city}") # 调用示例 add_school_to_city("school_votes.txt", "Chicago", "DJF, 204")
注:这个方法适合小文件,若处理超大文件,可改用临时文件逐行读写的方式,避免占用过多内存。
2. 计算各学校总得票数
用字典来统计票数最直接,遍历文件每一行,提取学校代码和票数后累加即可:
def calculate_total_school_votes(file_path): total_votes = {} with open(file_path, 'r') as f: for line in f: line = line.strip() # 跳过空行和城市标记行 if not line or line.startswith("City: "): continue # 分割学校代码和票数,处理可能存在的空格 school_code, vote_str = line.split(',') school_code = school_code.strip() votes = int(vote_str.strip()) # 累加票数 if school_code in total_votes: total_votes[school_code] += votes else: total_votes[school_code] = votes return total_votes # 调用示例 vote_result = calculate_total_school_votes("school_votes.txt") for school, total in vote_result.items(): print(f"{school} 总得票数:{total}")
运行后就能得到每个学校在所有城市的总票数,比如示例中WPE的总票数为239+456=695。
内容的提问来源于stack exchange,提问作者Hello World
相关产品推荐
相关产品推荐

