简体   繁体   中英

Python: Using delimiter to write into specific columns of csv file

I have an input text file with each line in the format

Line[X]: [AAA] [BBB] [CCC] :1234

I would like to use " : " as delimiter and write to each column into a excel file. I have tried the following code but not sure if this is the right approach. Any inputs are highly appreciated.

import csv
Text_File = open("some_text_file.txt", "w+")
csv_results = open ("Results.csv", 'w')

for eachline in Text_File:
    csv_results.writer(Text_File, delimiter ='**:**',quotechar='**:**', quoting=csv.QUOTE_MINIMAL)

Thanks!

import csv
txt = open("some_text_file.txt", "w+")
csv_results = open ("Results.csv", 'w')
text_reader = reader(txt)

#this delimiter is for your output file to be read by excel
csv_results.writer(Text_File, delimiter =',')

for line in txt:
    split_line = line.split(":")
    csv_results.writerow(split_line)


txt.close()
csv_results.close()

This should do what you want it to. If you want to remove the spaces on either side of the second column, you can probably use regex for that.

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