如何将csv文件从压缩文件夹从url加载到dataframe中

dkqlctbz  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(302)

我想把一个csv文件从一个压缩文件夹从一个url加载到一个数据框中。我在这里引用了相同的解决方案,如下所示:

from urllib import request
import zipfile

# link to the zip file

link = 'https://cricsheet.org/downloads/'

# the zip file is named as ipl_csv2.zip

request.urlretrieve(link, 'ipl_csv2.zip')
compressed_file = zipfile.ZipFile('ipl_csv2.zip')

# I need the csv file named all_matches.csv from ipl_csv2.zip

csv_file = compressed_file.open('all_matches.csv')
data = pd.read_csv(csv_file)
data.head()

但是在运行代码之后,我得到一个错误:

BadZipFile                                Traceback (most recent call last)
<ipython-input-3-7b7a01259813> in <module>
      1 link = 'https://cricsheet.org/downloads/'
      2 request.urlretrieve(link, 'ipl_csv2.zip')
----> 3 compressed_file = zipfile.ZipFile('ipl_csv2.zip')
      4 csv_file = compressed_file.open('all_matches.csv')
      5 data = pd.read_csv(csv_file)

~\Anaconda3\lib\zipfile.py in __init__(self, file, mode, compression, allowZip64, compresslevel, strict_timestamps)
   1267         try:
   1268             if mode == 'r':
-> 1269                 self._RealGetContents()
   1270             elif mode in ('w', 'x'):
   1271                 # set the modified flag so central directory gets written

~\Anaconda3\lib\zipfile.py in _RealGetContents(self)
   1334             raise BadZipFile("File is not a zip file")
   1335         if not endrec:
-> 1336             raise BadZipFile("File is not a zip file")
   1337         if self.debug > 1:
   1338             print(endrec)

BadZipFile: File is not a zip file

我不太习惯用python处理zip文件。所以,请帮助我在这里,我需要在我的代码中做什么更正?
如果我打开网址 https://cricsheet.org/downloads/ipl_csv2.zip 在web浏览器中,zip文件会自动下载到我的系统中。由于数据每天都被添加到这个zip文件中,我想访问url并通过python直接获取csv文件以节省存储空间。
如果你们有其他的代码解决方案,请分享。。。

7jmck4yq

7jmck4yq1#

试试这个:

link = "https://cricsheet.org/downloads/ipl_csv2.zip"

不用担心,如果文件被下载,取消下载,如果你不想要那个文件。您将始终从 link .

相关问题