zoukankan      html  css  js  c++  java
  • [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),这样写出的时候,一样也会因为文件操作模式问题,导致前面多条数据无法记录。  


      

  • 相关阅读:
    innerHTML使用方法
    HDU 1426 Sudoku Killer
    Junit使用教程(一)
    HLS协议实现
    GPIO
    TraceView总结
    在kettle中实现数据验证和检查
    用户向导左右滑动页面实现之ImageSwitcher
    DWZ使用笔记
    oracle进程
  • 原文地址:https://www.cnblogs.com/pxy7896/p/13390997.html
Copyright © 2011-2022 走看看