[英]convert text file column into csv file single row using pandas?
I have text file which look like this: txt file我有如下所示的文本文件: txt 文件
Now I want to convert that text file in csv file single row现在我想在 csv 文件单行中转换该文本文件
The outcome would look like: output结果看起来像: output
This is my code:这是我的代码:
with open("file.txt", "r") as fin,\
open("file.csv", "w") as fout:
col1, col2,col3,col4 = zip(*(line.rstrip().split() for line in fin))
fout.write(",".join(col1 + col2 +col4 +col5))
textfile:文本文件:
data1 data5 data9 data13 data2 data10 data14 data data7 data11 data15 data4 data12 data16 1 5 9 13 2 10 14 3 7 11 15 4 12 16 output: data1 data2 data3 data4 data5 data7 data10 data11.... data16 1 2 3 4 5 7 10 11.... 16
Try the following approach:尝试以下方法:
data10
being sorted before data1
.data10
在data1
之前排序。csv.writer()
to create the CSV file by transposing the entries into two rows.csv.writer()
通过将条目转换为两行来创建 CSV 文件。 For example:例如:
import re
import csv
with open('file.txt') as f_input:
data = re.findall('\w+', f_input.read())
items = len(data) // 2
with open('file.csv', 'w', newline='') as f_output:
kv = [(k, v) for k, v in sorted(zip(data[:items], data[items:]), key=lambda x: int(re.search('\d+', x[0]).group(0)))]
csv.writer(f_output).writerows(zip(*kv))
Giving you file.csv
containing:给你
file.csv
包含:
data1,data2,data3,data4,data5,data7,data9,data10,data11,data12,data13,data14,data15,data16
1,2,3,4,5,7,9,10,11,12,13,14,15,16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.