Python文件读写问题:仅写入最后一条URL如何修复?
解决写入文件仅保留最后一行的问题
嘿,我一眼就看出问题所在了——你的代码每次写入文件时都在覆盖原有内容,难怪最后只剩最后一条URL!
问题根源
你的writefile函数默认使用"wt"(文本写入)模式打开文件,这个模式的特性是:打开文件时会清空所有已有内容,然后写入新内容。所以在readfile的循环里,每处理一行URL就调用一次writefile,前两行生成的内容都会被后一行覆盖,最终文件里只剩最后一条的内容。
另外,原代码里还有个隐藏bug:twitter_name_before变量根本没定义,运行时会直接抛出NameError,这个也得一起修复。
两种修复方案
方案1:改用追加模式写入
把writefile的默认模式改成"at"(文本追加),这样每次写入都会把内容加到文件末尾,不会覆盖之前的内容。不过要注意,如果多次运行程序,文件会不断累加内容;如果需要每次运行都重新生成,得在开头先清空文件。
修改后的代码:
def readfile(filename,mode="rt"): head = "<li><a href=\"" center = "\" target=\"_blank\">" end ="<br></a></li>\n" # 加换行让内容更整洁 # 先清空目标文件,避免多次运行累加 writefile("C:/Users/Johny The Overlord/Documents/Code/test_1.txt", "") with open(filename,mode) as fin: for line in fin: link = line.strip() # 去掉换行和多余空格 if not link: continue # 可靠提取Twitter用户名 twitter_name = link.split("/")[-1] full_code = head+link+center+"@"+twitter_name+end writefile("C:/Users/Johny The Overlord/Documents/Code/test_1.txt",full_code, mode="at") def writefile(filename,contents,mode="wt"): with open(filename,mode) as fout: fout.write(contents) def main(): readfile("C:/Users/Johny The Overlord/Documents/Code/test.txt") if __name__ == "__main__": main()
方案2:先收集所有内容再一次性写入(更高效)
频繁打开关闭文件会影响效率,更好的做法是先把所有生成的HTML代码收集到一个列表里,最后一次性写入文件,这样只需要打开一次文件。
完整优化后的代码:
def readfile(filename, mode="rt"): head = "<li><a href=\"" center = "\" target=\"_blank\">" end = "<br></a></li>\n" content_buffer = [] # 用列表缓存所有内容 with open(filename, mode) as fin: for line in fin: link = line.strip() if not link: # 跳过空行 continue # 从URL中提取Twitter用户名 twitter_username = link.split("/")[-1] full_html = f"{head}{link}{center}@{twitter_username}{end}" content_buffer.append(full_html) # 一次性写入所有内容 writefile("C:/Users/Johny The Overlord/Documents/Code/test_1.txt", "".join(content_buffer)) def writefile(filename, contents, mode="wt"): with open(filename, mode) as fout: fout.write(contents) def main(): readfile("C:/Users/Johny The Overlord/Documents/Code/test.txt") if __name__ == "__main__": main()
关键改进点
- 用
line.strip()去除每行末尾的换行符和多余空格,避免生成的HTML出现无效空白。 - 用
split("/")[-1]可靠提取Twitter用户名,解决原代码中twitter_name_before未定义的问题。 - 方案2通过列表缓存内容,减少文件IO操作,效率更高,也从根源上避免了覆盖问题。
内容的提问来源于stack exchange,提问作者J. Sumittanun
相关产品推荐
相关产品推荐

