【问题标题】:Reading CSV file downloaded from FTP in Python not reading all rows在 Python 中读取从 FTP 下载的 CSV 文件不读取所有行
【发布时间】:2022-01-09 15:23:59
【问题描述】:

我正在尝试从 FTP 的文件夹中读取 CSV 文件。该文件有 3072 行。但是,当我运行代码时,它并没有读取所有行。底部的某些行被遗漏了。

## FTP host name and credentials
ftp = ftplib.FTP('IP', 'username','password')

## Go to the required directory
ftp.cwd("Folder_Name")

names = ftp.nlst()
final_names= [line for line in names if '.csv' in line]

latest_time = None
latest_name = None

#os.chdir(filepath)

for name in final_names:
    
    time1 = ftp.sendcmd("MDTM " + name)
    if (latest_time is None) or (time1 > latest_time):
        latest_name = name
        latest_time = time1

file = open(latest_name, 'wb')

ftp.retrbinary('RETR '+ latest_name, file.write)

dat = pd.read_csv(latest_name)

要从 FTP 读取的 CSV 文件如下-

代码的输出是as-

【问题讨论】:

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


【解决方案1】:

确保在尝试读取文件之前关闭文件,使用file.close(),或者更好的是使用with

with open(latest_name, 'wb') as file:
    ftp.retrbinary('RETR '+ latest_name, file.write)

dat = pd.read_csv(latest_name)

如果您不需要将文件实际存储到本地文件系统,并且文件不是太大,可以只下载到内存:
Reading files from FTP server to DataFrame in Python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2018-07-26
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多