简体   繁体   English

Python:使用定界符写入csv文件的特定列

[英]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. 我想使用“ ”作为分隔符,并将每一列写入excel文件。 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. 如果要删除第二列两边的空格,则可以为此使用正则表达式。

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

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