【问题标题】:Error on read gzip csv from url in Python: "_csv.Error: line contains NULL byte"在 Python 中从 url 读取 gzip csv 时出错:“_csv.Error: line contains NULL byte”
【发布时间】:2015-11-17 03:55:25
【问题描述】:

我正在尝试从 url 读取压缩后的 csv 文件。这是一个非常大的文件,超过 50.000 行。当我尝试下面的代码时出现错误:_csv.Error: line contains NULL byte

import csv
import urllib2   
url = '[my-url-to-csv-file].gz'
response = urllib2.urlopen(url)
cr = csv.reader(response)

for row in cr:
    if len(row) <= 1: continue
        print row

如果我在尝试读取文件之前尝试打印文件的内容,我会得到如下信息:

?M}?7?M==??7M???z?YJ?????5{Ci?jK??3b??p?

?[?=?j&=????=?0u'???}mwBt??-E?m??Ծ??????WM??wj??Z??ėe?D ?VF????4=Y?Y?tA???

我怎样才能正确地从这个 URL 读取压缩后的 csv 文件?

【问题讨论】:

  • 我认为你在这里不需要csv.reader...你试过response = urllib2.urlopen(url)data = response.read()response.close()for line in data: print line吗?
  • 如果我尝试这种方法,我会得到内容,但我认为它的编码错误,我会得到类似:% s Z ? o ? J 1 v ? } ? ? D ? ? ? ? ? ? ? ? ? ?
  • 试试for line in data: line = line.decode('utf-8') print linedocs.python.org/dev/tutorial/stdlib.html#internet-access
  • 是的,但我得到了错误,gzip 中的 csv 是否重要?
  • 这很重要;请参阅下面的答案。

标签: python csv gzip urllib2 urlopen


【解决方案1】:

如何从带有 urllib2.urlopen 的 URL 中打开 .gz (gzip) csv 文件

  1. 将 URL 数据保存到文件对象。为此,您可以使用StringIO.StringIO()
  2. 使用gzip.Gzipfile()解压.gz。
  3. 从新文件对象中读取数据。

使用您的示例:

from StringIO import StringIO
import gzip
import urllib2

url = '[my-url-to-csv-file].gz'
mem = StringIO(urlopen(url).read())
f = gzip.GzipFile(fileobj=mem, mode='rb')
data = f.read()

for line in data:
  print line

【讨论】:

    【解决方案2】:

    使用 try 和 except,如果您不在乎遇到 NULL 行时会发生什么,只需使用 pass

    for row in cr:
        try:
            if len(row) <= 1: continue
                print row
        except Exception, e:
            print e
            #or if you're not worried about errors, you can use pass
    

    【讨论】:

    • 埃加德!这绝对不理想 - stackoverflow.com/questions/21553327/…
    • 当然,这是真的。他们也可以这样做:except Exception, e: print e,然后他们可以读取他们的数据,而不会被NULL 字节中断。
    • 奇怪我仍然得到同样的错误,但错误在 for row in cr:
    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多