nipy
nipy

Reputation: 5508

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']

Upvotes: 1

Views: 105

Answers (2)

Brian
Brian

Reputation: 248

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

Upvotes: 0

Artyom Vancyan
Artyom Vancyan

Reputation: 5388

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")

Upvotes: 1

Related Questions