• Python中通过csv的writerow输出的内容有多余的空行


    第一种方法

    如下生成的csv文件会有多个空行

    import csv
    
    #python2可以用file替代open
    with open("test.csv","w") as csvfile: 
        writer = csv.writer(csvfile)
    
        #先写入columns_name
        writer.writerow(["index","a_name","b_name"])
        #写入多行用writerows
        writer.writerows([[0,1,3],[1,2,3],[2,3,4]])

    加入newline='' 参数

    #coding=utf-8
    import csv
    
    #python2可以用file替代open
    with open("test.csv","wt",newline='') as csvfile: 
        writer = csv.writer(csvfile)
        #写入多行用writerows
        writer.writerows([["index","a_name","b_name"],[0,1,3],[1,2,3],[2,3,4]])

    这样就不会有空行了。


    第二种方法:

    先写入csv文件,然后读出去掉空行,再写入

    with open('E:\test.csv','wt')as fout:       #生成csv文件,有空行
        cout=csv.DictWriter(fout,list_attrs_head )
        cout.writeheader()
        cout.writerows(list_words)
    with open('E:\test.csv','rt')as fin:  #读有空行的csv文件,舍弃空行
        lines=''
        for line in fin:
            if line!='
    ':
                lines+=line
    with open('E:\test.csv','wt')as fout:  #再次文本方式写入,不含空行
        fout.write(lines)

    参考:

    https://www.crifan.com/python_csv_writer_writerow_redundant_new_line/?utm_source=tuicool&utm_medium=referral

    https://blog.csdn.net/langaer/article/details/70052971

  • 相关阅读:
    网卡的ring buffer
    vm 缓存相关参数配置
    网卡TSO/GSO特性
    物理主机BIOS设置
    jquery_元素文本值、属性值的获取、修改、添加(text、prop、attr、css)
    jquery_页面加载方式
    jquery_新增元素
    jquery_事件
    Django_POST请求的CSRF验证
    jquery_定位元素
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10310471.html
Copyright © 2020-2023  润新知