Search code examples
pythonpython-3.xcsvftpftplib

I'm having problems binary reading a .csv to a dictionary


I'm reading a .CSV file from an FTP server, and would like to convert its content to a dictionary.

There is some problem when reading to csv.DictReader.

from ftplib import FTP
from io import BytesIO
import csv
ftp = FTP('192.168.202.90')    
loggedOn = ftp.login(user='admin', passwd='admin')
loggedOn = loggedOn.endswith('OK') # '230 Login OK'  
if loggedOn:
    ftp.cwd('/CSV')
    Files = ftp.nlst()
    NewestFile = Files[-1] # last file in the list
    r = BytesIO()
    ftp.retrbinary('RETR '+NewestFile, r.write)
    data = r.getvalue().decode("utf-8")
    print(r.getvalue())
    print(data)
    for row in csv.DictReader(data, delimiter=','):
        print(row)
    ftp.close()

OUTPUT OF 'print(r.getvalue())':

b'CheckBox_T100,TestedDatetime\nYes,2020-05-24'

OUTPUT OF 'print(data):

CheckBox_T100,TestedDatetime
Yes,2020-05-24

OUTPUT OF for loop 'print()':

{'C': 'h'}
{'C': 'e'}
{'C': 'c'}
{'C': 'k'}
{'C': 'B'}
{'C': 'o'}
{'C': 'x'}
{'C': '_'}
{'C': 'T'}
{'C': '1'}
{'C': '0'}
{'C': '0'}
{'C': '', None: ['']}
{'C': 'T'}
{'C': 'e'}
{'C': 's'}
{'C': 't'}
{'C': 'e'}
{'C': 'd'}
{'C': 'D'}
{'C': 'a'}
{'C': 't'}
{'C': 'e'}
{'C': 't'}
{'C': 'i'}
{'C': 'm'}
{'C': 'e'}
{'C': 'Y'}
{'C': 'e'}
{'C': 's'}
{'C': '', None: ['']}
{'C': '2'}
{'C': '0'}
{'C': '2'}
{'C': '0'}
{'C': '-'}
{'C': '0'}
{'C': '5'}
{'C': '-'}
{'C': '2'}
{'C': '4'}

how do I get a proper directory

{'CheckBox_T100': 'Yes', 'TestedDatetime': '2020-05-24'}

Solution

  • Found the solution myself. I had to include StringIO as well.

    from ftplib import FTP
    from io import BytesIO
    from io import StringIO
    import csv
    ftp = FTP('192.168.202.90')    
    loggedOn = ftp.login(user='admin', passwd='admin')
    loggedOn = loggedOn.endswith('OK') # '230 Login OK'  
    if loggedOn:
        ftp.cwd('/CSV')
        Files = ftp.nlst()
        NewestFile = Files[-1] # last file in the list
        r = BytesIO()
        ftp.retrbinary('RETR '+NewestFile, r.write)
        data = r.getvalue().decode("utf-8")
        for row in csv.DictReader(StringIO(data)):
            print(row)
        ftp.close()