0

I have code as follows:

try:
    relations = open(file_name, "wb")      
    ftp.retrbinary('RETR {0}'.format(file_name), test)         
    relations.close()  # Closes the local file        
    ftp.quit()  # Closes the ftp connection
    print("FTP Connection quited.")        
except Exception as e:
    print("Error: File {0} could not be downloaded. {1}".format(file_name, str(e)))

And the test function is as follows:

def test(data):
    data_n = json.dumps(data.decode('utf-8'))

    pdb.set_trace()
    pass

I want to download the file from ftp server using python and read it without writing it locally.

In this case in test function in data_n i get:

'"CODE;MATCHCODE;\\r\\nK902154;VANHOVEGARAGES;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\\r\\nK902191;CARAVENUESTAR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\\r\\nK902192;CARAVENUESTAR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"'

How can I convert it to the list of dictionaries as follows:

result = [
    {
        "CODE": "K902154",
        "MATCHCODE": "VANHOVEGARAGES"
    },
    {
        "CODE": "K902191",
        "MATCHCODE": "CARAVENUESTAR"
    },
    {
        "CODE": "K902192",
        "MATCHCODE": "CARAVENUESTAR"
    }
]
2
  • It looks like you’re getting actual backslashes in that string, instead of newlines — is that correct? Commented May 13, 2019 at 10:15
  • @TomZych Yes. Its correct. Commented May 13, 2019 at 10:16

1 Answer 1

1

Using str.split and a simple iteration.

Ex:

s = '"CODE;MATCHCODE;\\r\\nK902154;VANHOVEGARAGES;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\\r\\nK902191;CARAVENUESTAR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\\r\\nK902192;CARAVENUESTAR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"'
result = []
for i, v in enumerate(s.split(r"\r\n")):
    if i == 0:
        keys = v.strip().strip(';"').split(";")    #Get Keys
    else:
        result.append(dict(zip(keys, v.strip().strip(';"').split(";"))))     #Form dict. 

print(result)

Output:

[{'CODE': 'K902154', 'MATCHCODE': 'VANHOVEGARAGES'},
 {'CODE': 'K902191', 'MATCHCODE': 'CARAVENUESTAR'},
 {'CODE': 'K902192', 'MATCHCODE': 'CARAVENUESTAR'}]
Sign up to request clarification or add additional context in comments.

1 Comment

Updated snippet. Can you try this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.