简体   繁体   English

将列表拆分为csv中的单独列

[英]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. 我试图拆分我在Python中创建的列表,然后制作一个独立列的csv文件,每个变量都有自己的列。 The variables of the list are separated by the delineator "|". 列表的变量由定界符“ |”分隔。 This List looks something looks like: 1234|11/20/2017|4. 该列表看起来像: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. 因此,当我创建列表的csv时,它仅构成列表的一列,因此现在需要拆分列表,并使用3个不同的列创建另一个csv。 Thanks!! 谢谢!!

Use the built in csv module: 使用内置的csv模块:

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) (归功于Clinton W. Brownley ..《使用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. print命令仅用于将输出显示在屏幕上进行检查,以及sys模块导入,以防您想要使其自动化并馈入不同的csv文件。 in_path variable will than be: in_path = sys.argv[1] out_path = sys.argv[2] in_path变量将是: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. sys argv方法首先从命令行[1]读取文件路径(在python脚本之后),然后从[2]读取文件路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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