简体   繁体   中英

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?

Desired output

Is a CSV which will be imported into Pandas:

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

etc..

Updated desired output as per comments to 6 rows.

Updated. I can get the first row like this if I assign the string to l variable:

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. You wouldn't need to export the data prior to importing with pandas if you use something like this.

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

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