gpt4 book ai didi

Python:直接从web获取CSV,导致数据无法使用

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:17 24 4
gpt4 key购买 nike

我在 Windows 上使用 Python 3.5。

我有这段代码可以从存储在 Links.txt 中的不同 URL 下载将近一百个 CSV 文件:

from urllib import request

new_lines = 'None'


def download_data(csv_url):
response = request.urlopen(csv_url)
csv = response.read()
csv_str = str(csv)
global new_lines
new_lines = csv_str.split("\\n")

with open('Links.txt') as file:
for line in file:
URL = line
file_name = URL[54:].rsplit('.ST', 1)[0]
download_data(URL)
save_destination = 'C:\\Download data\\Data\\' + file_name + '.csv'
fx = open(save_destination, "w")
for lines in new_lines:
fx.write(lines+"\n")
fx.close()

问题是生成的 CSV 文件总是以 b ' 开头,在数据的最后一行之后是另一个 ' 和几个空行来包装东西向上。当我从浏览器查看文件时(在我下载它们之前),我没有看到这些字符。

当我想导入和使用数据库中的数据时,这会产生问题。您是否知道为什么会发生这种情况以及我如何获得正确写入 CSV 文件的代码?

可以使代码更快/更好的提示,或针对代码中其他缺陷的调整显然非常受欢迎。

最佳答案

发生的事情是 urllib 将其流视为字节 - 任何看起来像 b'...' 的字符串都意味着它是字节串。

您的直接问题可以通过调用 decode('utf-8')(如 Chedy2149 所示)对流进行编码来解决,这将转换数据的字节。

但是,您可以通过将文件直接下载到磁盘来完全消除此问题。您完成了下载、拆分和写入磁盘的工作,但这一切似乎都是不必要的,因为您的代码最终只是将文件的内容写入磁盘,而无需对它们进行额外的工作。

您可以使用 urllib.request.urlretrieve并直接下载到文件。

这是根据您的代码修改的示例。

import urllib.request

def download_data(url, file_to_save):
filename, rsp = urllib.request.urlretrieve(url, file_to_save)
# Assuming everything worked, the file has been downloaded to file_to_save

with open('Links.txt') as file:
for line in file:
url = line.rstrip() # adding this here to remove extraneous '\n' from string
file_name = url[54:].rsplit('.ST', 1)[0]
save_destination = 'C:\\Download data\\Data\\' + file_name + '.csv'
download_data(url, save_destination)

关于Python:直接从web获取CSV,导致数据无法使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com