2017-09-26 120 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