Python文件读写故障:处理后仅写入最后一行,寻求修复方案
修复文件遍历写入仅保留最后一行的问题
嘿,我太懂你这个问题了!这种每次写入都只留最后一行的情况,基本都是文件打开模式和时机搞错了。先看看你的代码问题出在哪:
你大概率是在每一行的循环里用'w'模式打开输出文件——这个模式的特性就是:每次打开时会直接清空文件里原有的所有内容!所以你循环处理一行就写一次,前面写的内容全被后面的覆盖了,最后自然只剩最后一行的结果。
给你两种修复方案,优先选第一种,效率更高也更安全:
方案一:一次性打开输出文件(推荐)
用Python的with语句同时打开输入和输出文件,这样只打开一次输出文件,循环里的每次写入都会追加到文件末尾,不会覆盖:
def generate_daily_totals(input_filename, output_filename): """Returns date followed by the sum of values""" # with语句会自动帮我们关闭文件,不用手动调用close() with open(input_filename, 'r') as infile, open(output_filename, 'w') as outfile: for line in infile: # 先处理掉空行和首尾空格,避免拆分出错 cleaned_line = line.strip() if not cleaned_line: continue content = cleaned_line.split(",") date = content[0] total = 0.0 for value in content[1:]: # 加个异常处理,防止遇到非数字值导致程序崩溃 try: total += float(value) except ValueError: print(f"⚠️ 警告:行'{cleaned_line}'中的值'{value}'不是有效数字,已跳过") # 把处理后的结果写入文件 outfile.write(f"{date},{total}\n")
方案二:用追加模式打开文件(不推荐,效率低)
如果因为某些原因必须在循环内打开文件,那一定要用'a'(追加)模式,而不是'w':
def generate_daily_totals(input_filename, output_filename): """Returns date followed by the sum of values""" with open(input_filename, 'r') as infile: for line in infile: cleaned_line = line.strip() if not cleaned_line: continue content = cleaned_line.split(",") date = content[0] total = 0.0 for value in content[1:]: try: total += float(value) except ValueError: print(f"⚠️ 警告:行'{cleaned_line}'中的值'{value}'不是有效数字,已跳过") # 用'a'模式打开,新内容会追加到文件末尾,不会覆盖原有内容 with open(output_filename, 'a') as outfile: outfile.write(f"{date},{total}\n")
关键知识点提醒:
'w'模式:打开文件时会清空所有原有内容,适合一次性写入全部数据的场景。'a'模式:打开文件时保留原有内容,新写入的内容会加到文件最后。with语句:Python里处理文件的最佳实践,自动管理文件资源,避免忘记关闭文件导致的各种问题。
内容的提问来源于stack exchange,提问作者user9644895
相关产品推荐
相关产品推荐

