2017-09-26 103 views
0

我在安全的FTP服务器上有一组CSV文件,我尝试在内存中读入(单独)Pandas DataFrame,以便操纵它们然后通过API将它们传递到别处。 FTP服务器需要验证,这意味着我无法使用其他非常有用的pd.read_csv()直接从服务器读取csv。如何从安全FTP服务器读取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文件,但是当文件在登录后进行门控时,我看不到任何如何操作的示例。

回答

0

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