简体   繁体   English

在 Python 中将多行字符串转换为 csv

[英]Transform multi-row string to csv in Python

What is the best way to take this string:获取此字符串的最佳方法是什么:

1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d

and transform to a CSV containing 6 columns?并转换为包含 6 列的 CSV?

Desired output期望输出

Is a CSV which will be imported into Pandas:是将导入 Pandas 的 CSV:

1,a,1,a,1,a
2,b,2,b,2,b

etc..等等..

Updated desired output as per comments to 6 rows.根据评论将所需的输出更新为 6 行。

Updated.更新。 I can get the first row like this if I assign the string to l variable:如果我将字符串分配给l变量,我可以获得这样的第一行:

l.split()[0::4]

['1', 'a', '1', 'a', '1', 'a']
with open('data.txt', 'r') as f:
    data = f.read().split("\n") 
    for i in range(4):
        d = list()
        for j in range(i, len(data), 4):
            d.append(data[j])
        with open('data.csv', 'a') as csv:
            csv.write(','.join(d)+"\n")

Even though Art's answer is accepted, here is another way using pandas.尽管接受了 Art 的答案,但这是使用 Pandas 的另一种方式。 You wouldn't need to export the data prior to importing with pandas if you use something like this.如果你使用这样的东西,你就不需要在用 Pandas 导入之前导出数据。

import pandas as pd


myFile="lines_to_read2.txt"
myData = pd.DataFrame (columns=['col1', 'col2', 'col3','col4'])
mycolumns = 4
thisItem = list()

with open(myFile, 'r') as linesToRead:
    for thisLine in linesToRead:
        thisItem.append(thisLine.strip('\n, " "'))
        if len(thisItem) == mycolumns:
            myData = myData.append({'col1':thisItem[0],'col2':thisItem[1],'col3':thisItem[2],'col4':thisItem[3]}, ignore_index=True)
            thisItem = list()

myData.to_csv('lines_as_csv_file.csv', index=False)
print(myData)   # Full Table

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

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