【问题标题】:How do I read a CSV from Secure FTP Server into a Pandas DataFrame如何从安全 FTP 服务器读取 CSV 到 Pandas DataFrame
【发布时间】:2017-09-26 22:46:47
【问题描述】:

我在一个安全的 FTP 服务器上有一组 CSV 文件,我试图将它们读入内存中的(单独的)Pandas DataFrame,以便我可以操作它们,然后通过 API 将它们传递到其他地方。 FTP 服务器需要身份验证,这意味着我无法使用其他非常有用的 pd.read_csv() 直接从服务器读取 csv。

以下 (Python 3.x) 代码将连接然后将文件写入磁盘:

from ftplib import FTP
import pandas as pd

server = "server.ip"
username = "user"
password = "psswd"

file1 = "file1.csv"  # Just one of the files; I'll eventually loop through...

ftp = FTP(server)
ftp.login(user=username, passwd=password)

with open(filename, "wb") as file:
    ftp.retrbinary("RETR " + filename, file.write)

# Do some other logic not relevant to the question

我想避免将文件写入磁盘然后再将其读回。我知道pd.read_csv() 将直接从公共地址读取 csv 文件,但我看不到任何示例说明如何这样做文件在登录后被封闭。

【问题讨论】:

    标签: python python-3.x pandas csv ftp


    【解决方案1】:

    IIRC 您可以使用 urllib2 执行经过身份验证的 FTP 请求。也许像

    import urllib2, base64
    import pandas as pd
    
    req = urllib2.Request('ftp://example.com')
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string) 
    response = urllib2.urlopen(req)
    data = pd.csv_read(response.read())
    

    未经测试,但您可以找到更多信息urllib2 here

    【讨论】:

      【解决方案2】:

      感谢John Zwinck

      import pandas as pd
      import pysftp as sftp
      
      with sftp.connect(your_host, your_user, your_pw) as conn:
          with conn.open("path_and_file.csv", "r") as f:
              df = pd.read_csv(f)
      

      它工作得很好。最好的问候。

      【讨论】:

        猜你喜欢
        • 2021-11-11
        • 1970-01-01
        • 2021-08-10
        • 1970-01-01
        • 2011-01-11
        • 2017-09-05
        • 2020-11-07
        • 2015-05-23
        • 1970-01-01
        相关资源
        最近更新 更多