即使使用有效的换行符,Python csv库也会留空行 [英] Python csv library leaves empty rows even when using a valid lineterminator

查看:86
本文介绍了即使使用有效的换行符,Python csv库也会留空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从互联网上获取数据以将其保存到csv文件中.
我在写入csv文件时遇到问题,该库在文件中留下了空行

I am trying to fetch data from the internet to save it to a csv file.
I am facing a problem with writing to the csv file, the library leaves an empty row in the file

数据是text/plain格式的random.org整数.


我正在使用urllib.request来获取数据,并且正在使用此代码来获取数据并对其进行解码

The data is random.org integers in text/plain format.


I'm using urllib.request to fetch the data and I am using this code to get the data and decode it

req = urllib.request.Request(url, data=None, headers={
    'User-Agent': '(some text)'})

with urllib.request.urlopen(req) as response:
    html = response.read()
    encoding = response.headers.get_content_charset('utf-8')
    data = html.decode(encoding)

我正在使用以下代码打开csv文件: csvfile = open('data.csv',"a")
写入文件:
writer = csv.writer(csvfile,lineterminator ='\ n')writer.writerows(data)
当然我会在最后关闭文件


我尝试过但没有帮助的事情:

I am using this line of code to open the csv file :csvfile = open('data.csv', "a")
Writing to the file:
writer = csv.writer(csvfile, lineterminator = '\n') writer.writerows(data)
and of course I close the file at the end


Things I tried and didn't help :

  • 编写时使用(lineterminator ='\ n')
  • 打开文件时使用(newline =")
  • 定义定界符","quotechar"和"quoting"

推荐答案

更新后的答案

如果在创建要写入 data 列表的列表时,如果将其添加为列表,以使 data 成为列表列表,则进行设置您的行定界符为'\ n',它应该可以正常工作.下面是我用来测试的工作代码.

If when you create the list that is being written to the data list, if you add it as a list so that data becomes a list of lists, then set your line delimiter to be '\n', it should work. Below is the working code I used to test.

import csv
import random

csvfile = open('csvTest.csv', 'a')
data = []
for x in range(5):
    data.append([str(random.randint(0, 100))])

writer = csv.writer(csvfile, lineterminator = '\n')
writer.writerows(data)
csvfile.close()

它会输出

这篇关于即使使用有效的换行符,Python csv库也会留空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆