[DEBUG] python写文件时print漏掉整行数据

问题描述

我有下面一段代码:

out_f = open("test.txt","w")
d = {"我是一个词典":"我有很多数据但是我不想写"}
for trans,oid in d.items():
    # 数据库配置语句省略
    # ...
    sql = 'insert into table_a(p, a_id, created, p_id) values("%s",999,now(),(select id from table_b where name="%s"));'%(trans, oid)
    print(sql + "
")
    out_f.write(sql + "
")

out_f.close()

d大概有175个键值对,print到控制台确实有175条,但写出到文件test.txt(代码执行前无此文件),确只有81条。整段代码没有报错,写出到文件直接省略了94条。

解决办法

在使用文件操作模式w时,其实要考虑缓冲区?前94条,可能直接被冲掉了,并没有保存到文件中。只要换成a模式,追加式写,则全部记录可以写出。

out_f = open("test.txt","a")

其实包括with open(“test.txt”,“w”) as file,再用print(内容,file=file),这样写出的时候,一样也会因为文件操作模式问题,导致前面多条数据无法记录。  


  

原文地址:https://www.cnblogs.com/pxy7896/p/13390997.html