【问题标题】:Download CSV files via FTP with Python ftplib to Dataframe - [Errno 2] No such file or directory使用 Python ftplib 通过 FTP 将 CSV 文件下载到 Dataframe - [Errno 2] 没有这样的文件或目录
【发布时间】:2022-10-07 16:50:26
【问题描述】:

尝试将文件从 ftp 服务器下载到 pandas 数据帧时,我收到 [Errno 2] No such file or directory 错误。这些文件位于 ftp 的根目录中。 当我打印

我猜pd.read_csv() 函数正在查看我的本地文件系统......即脚本所在的本地路径......但我不明白如何改变它。

def fetch_files(site, username, password, directory: str = \'/\', filematch: str = \'*.csv\'):
    with ftplib.FTP(site) as ftp:
        # pass the url without protocol
        ftp = ftplib.FTP(site)
        # pass credentials if anonymous access is not allowed
        ftp.login(username, password)
        ftp.cwd(directory)
        list_ = []
        for file_ in ftp.nlst(filematch):
            print(file_) # This works
            df = pd.read_csv(file_, index_col=None, header=0) # This fails
            list_.append(df)

还是我必须使用 ftp.retrlines() 方法? IF 那么 \'LIST\' \'MLSD\' 参数有什么区别?

附带说明:CSV 中的文件中包含 HTML 代码,例如 & ,它会推出 sql 批量插入。我将它们读取到数据框的原因是更改编码并合并单个文件。有没有更快的方法直接通过 python csv 模块执行此操作?我想这会更快?

先感谢您

    标签: python pandas path ftp ftplib


    【解决方案1】:

    使用FTP.retrbinaryBytesIO 将文件下载到内存,然后将内存中的类文件对象传递给read_csv

    flo = BytesIO()
    ftp.retrbinary('RETR ' + file_, flo.write)
    flo.seek(0)
    pd.read_csv(flo, ...)
    

    类似问题:Reading files from FTP server to DataFrame in Python

    【讨论】:

      猜你喜欢
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      相关资源
      最近更新 更多