Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert txt python dictionary file to csv data file?

I have a text file with 300,000 records. A sample is below:

{'AIG': 'American International Group', 'AA': 'Alcoa Corporation', 'EA': 'Electronic Arts Inc.'}

I would like to export the records into a csv file like this:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried the following, but it does not put any line breaks between the records. So in excel, the 300,000 records are in two rows, which doesn’t fit everything (16,000 column limit in Excel).

import pandas as pd

read_file = pd.read_csv (r'C:\...\input.txt')
read_file.to_csv (r'C:\...\output.csv', index=None)

>Solution :

You can try:

import pandas as pd
from ast import literal_eval

with open('your_file.txt', 'r') as f_in:
    data = literal_eval(f_in.read())

df = pd.DataFrame([{'Ticker': k, 'Name': v} for k, v in data.items()])
print(df)

# to save to CSV:
#df.to_csv('out.csv', index=False)

Prints:

  Ticker                          Name
0    AIG  American International Group
1     AA             Alcoa Corporation
2     EA          Electronic Arts Inc.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading