【问题标题】:Pandas: I am trying to open a specific .txt file stored in a zip file on an ftp sitePandas:我正在尝试打开存储在 ftp 站点上的 zip 文件中的特定 .txt 文件
【发布时间】:2016-07-01 10:39:51
【问题描述】:

我需要将来自this ftp 站点的每个 zip 文件中的每个 produkt_monat_Monatswerte_18910101_20110331_00003.txt 文件连接到一个框架中。

这是我目前使用的代码:

    import pandas as pd
    from pandas.io.parsers import *
    import glob
    import requests
    from zipfile import ZipFile
    import urllib.request as ur


    years = 'produkt_monat_Monatswerte_*.txt'

names = pd.DataFrame()
for year in years:
    path ="ftp://ftp-cdc.dwd.de/pub/CDC/observations_germany/climate/monthly/kl/historical/monatswerte_?????_????????_????????_hist.zip").read()
    frame = pd.read_csv(path, names=columns)

    frame['year'] = year
    names = names.concat(frame, ignore_index=True)

它给了我以下错误:

 File "<ipython-input-25-d57a1d77ecc6>", line 5
    path ="ftp://ftp-cdc.dwd.de/pub/CDC/observations_germany/climate/monthly/kl/historical/monatswerte_?????_????????_????????_hist.zip")

【问题讨论】:

  • 您的第一个问题是 glob 位它无法打开文件,您需要先解决该步骤,然后熊猫才能尝试打开它

标签: python pandas ftp zip


【解决方案1】:

问题是您不能让 pandas 从 Zip 中提取内部文件。 试试下面的代码:

import pandas as pd
from ftplib import FTP
import os
from zipfile import ZipFile
from io import BytesIO

f_root = 'ftp-cdc.dwd.de'
zips_path = '/pub/CDC/observations_germany/climate/monthly/kl/historical/'

ftp = FTP(f_root)

ftp.login()

ftp.cwd(zips_path)

paths = [p[0] for p in ftp.mlsd('.') if p[0].endswith('.zip')]

dfs = []

for path in paths:
    buf = BytesIO()
    ftp.retrbinary("RETR " + path, lambda block: buf.write(block))
    z = ZipFile(buf)

    zi = list(filter(lambda x: x.filename.startswith('produkt'), z.filelist))[0]
    df = pd.read_csv(BytesIO(z.read(zi.filename)), sep=';', encoding="cp1252")
    dfs.append(df)

final = pd.concat(dfs)

【讨论】:

  • 感谢您的回复。如何创建一个循环来连接所有这些
  • dfs = [] for path in paths: buf = BytesIO() ftp.retrbinary("RETR " + path, lambda block: buf.write(block)) z = ZipFile(buf) zi = list(filter(lambda x: x.filename.startswith('produkt'), z.filelist))[0] df = pd.read_csv(BytesIO(z.read(zi.filename)), sep=';', encoding="cp1252") dfs.append(df) final = pd.concat(dfs)(评论有点乱,我只是添加了一个循环。)
  • 谢谢! :) 你认为你可以用这个 ^ 评论更新你的答案吗?
  • 我已经用上面的评论更新了你的答案。你能看一下吗。它给了我一个错误。
  • 是的,commets 中的空格弄乱了……现在编辑它。
猜你喜欢
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 2016-07-27
  • 1970-01-01
  • 2021-06-06
  • 2010-09-12
相关资源
最近更新 更多