简体   繁体   中英

Splitting a List into separate columns in csv

I am trying to split a List I created in Python, and then make a csv file of separate columns with each variable having its own column. The variables of the list are separated by the delineator "|". This List looks something looks like: 1234|11/20/2017|4. So when I create a csv of the List its makes just one column of the List, so I now need to split the List and create another csv with the 3 different columns. Thanks!!

Use the built in csv module:

import sys
import csv

in_path = '/YOUR/ORIGINAL/FILE/PATH.csv'
out_path = '/THE/CORRECTED/FILE/HERE.csv'
with open(in_path, 'r', newline = '') as csv_in_file:
    with open(out_path, 'w', newline ='') as csv_out_file:
        reader = csv.reader(csv_in_file, delimiter='|')
        writer = csv.writer(csv_out_file, delimiter=',')
        for row in reader:
            print(row)
            writer.writerow(row)

the delimiter here changes from '|' to ',' for a Comma Seperated Values file. ( credit to Clinton W. Brownley.. author of Foundations For Analytics With Python)

the print command is just for getting the output on screen for checking and the sys module import for incase you would like to automate it and feed-in different csv files. in_path variable will than be: in_path = sys.argv[1] out_path = sys.argv[2]

and the execution from the command line will be:

python the_script.py /original/file/path.csv  corrected/file/path.csv

sys argv method reads the file path from the command line [1] for first ( after the python script) and [2] the second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM