首页 > 解决方案 > 使用python将CSV文件从FTPS服务器写入数据帧

问题描述

我正在尝试从 ftps 服务器中获取 csv 文件。不过,我收到了这个信息:

file = r'filename.csv'

with ftplib.FTP() as ftp:
    
    with open(file, 'rb') as f: 
        ftp.retrbinary(file, f.read)
        df1= pd.read_csv(file)
        df1.head()

有这个特殊的错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-a2725f958d45> in <module>
      4 
      5     with open(file, 'rb') as f:
----> 6         ftp.retrbinary(file, f.read)
      7         df1= pd.read_csv(file) #delimiter = '|', encoding = 'latin1')
      8         df1.head()

~\AppData\Local\Continuum\anaconda3\lib\ftplib.py in retrbinary(self, cmd, callback, blocksize, rest)
    439           The response code.
    440         """
--> 441         self.voidcmd('TYPE I')
    442         with self.transfercmd(cmd, rest) as conn:
    443             while 1:

~\AppData\Local\Continuum\anaconda3\lib\ftplib.py in voidcmd(self, cmd)
    275     def voidcmd(self, cmd):
    276         """Send a command and expect a response beginning with '2'."""
--> 277         self.putcmd(cmd)
    278         return self.voidresp()
    279 

~\AppData\Local\Continuum\anaconda3\lib\ftplib.py in putcmd(self, line)
    197     def putcmd(self, line):
    198         if self.debugging: print('*cmd*', self.sanitize(line))
--> 199         self.putline(line)
    200 
    201     # Internal: return one line from the server, stripping CRLF.

~\AppData\Local\Continuum\anaconda3\lib\ftplib.py in putline(self, line)
    192         if self.debugging > 1:
    193             print('*put*', self.sanitize(line))
--> 194         self.sock.sendall(line.encode(self.encoding))
    195 
    196     # Internal: send one command to the server (through putline())

AttributeError: 'NoneType' object has no attribute 'sendall'

关于为什么不将请求的文件放入数据框中的任何想法?

标签: python-3.x

解决方案


方法名称:三元法

retrbinary(cmd,回调,blocksize=8192,rest=None)

callback:对于从 FTP 服务器接收到的每个数据块,都会调用回调函数。该回调函数可用于处理接收到的数据。例如,回调可用于接收到的块写入文件

例如:你可以使用这个:

fhandle = open(filename, 'wb')
ftp.retrbinary('RETR ' + filename, fhandle.write)

或者

ftp.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)

推荐阅读