`_csv.Error: line contains NUL` from a downloaded csv

`_csv.Error: line contains NUL` from a downloaded csv

我从 url 下载了一个 csv 文件并使用 csv.reader 阅读了它的内容。但是,当我尝试遍历 _csv.reader 对象时,我得到 _csv.Error: line contains NUL

我必须提到 如果我手动复制粘贴(ctrl+a, ctrl+cctrl+v)csv 的内容手动到不同的 csv 代码工作。

这是目前为止的代码。

import csv
import requests

url='https://sedo.com/fileadmin/documents/resources/expiring_domain_auctions.csv'

response=requests.get(url)

with open('downloaded_csv.csv','wb') as out_file:
    out_file.write(response.content) # file is written properly in disk, can open with editor

with open('downloaded_csv.csv',newline='') as in_file:
    csv_contents=csv.reader(in_file,delimiter=';')
    print((csv_contents))
    for row in csv_contents: # _csv.Error: line contains NUL
        print(row)

谁能告诉我如何在我的 python 程序中读取这个文件的内容?

文件编码为UTF-16,因此读取文件时必须指定此编码。

>>> # Check the first 100 characters...
>>> r = requests.get(url)
>>> r.content.decode('utf-16')[:100]
'sep=;\n"Domain Name";"Start Time";"End Time";"Reserve Price";"Domain is IDN";"Domain has hyphen";"Dom'

根据您的平台,您需要像这样打开文件:

with open('downloaded_csv.csv', newline='', encoding=encoding) as in_file:

其中编码的值为utf-16, utf-16-le, utf-16-be

之一

请注意,您可能需要删除或跳过开头的 "sep=;" 行。