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

PYTHON: How do I create one .xlsx file that merges three .txt files into their own columns?

Here are the .txt files where the colon represents the beginning of the file:

City.txt:
New York
Chicago
Sacramento

County.txt:
New York County
Chicago County
Sacramento County

State.txt:
New York
Illinois
California

Here is my code so far:

columnCity1 = open('City.txt', 'r')
columnCounty2 = open('County.txt', 'r')
columnState3 = open('State.txt', 'r')

This imports the files and creates them as a list (to my understanding)

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

The desired outcome would be:

enter image description here

>Solution :

Under assumption that csv file can be used for Excel and you can reformat it if needed or just open, here’s a Pandas solution (you’ll need Pandas installed):

import pandas as pd


def read_files():
    # Read all lines, get rid of empty entries and next line characters
    with open('./city.txt', 'r') as f:
        cities = [c.rstrip()  for c in f.readlines() if len(c.rstrip())]

    with open('./county.txt', 'r') as f:
        counties = [c.rstrip() for c in f.readlines() if len(c.rstrip())]

    with open('./state.txt', 'r') as f:
        states = [s.rstrip()  for s in f.readlines() if len(s.rstrip())]


    # Create dataframe
    df = pd.DataFrame(columns=['City', 'County', 'State'])

    # Go over cities, countries and states - place in DataFrame
    for group in zip(cities, counties, states):
        df.loc[len(df)] = group

    # Save to csv file - reformat to excel if different format needed.
    filename = 'results.csv'
    df.to_csv(filename)

#Call the above function - check the resulting file for output.
read_files()
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