1

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']
4
  • 1
    Could you show us what you have tried so far ? Commented Feb 19, 2020 at 18:01
  • 1
    I see 4 columns here, not 6., Commented Feb 19, 2020 at 18:10
  • How are you deciding where to put each item? Commented Feb 19, 2020 at 18:10
  • Please see my update which shows how I get the first row and explains the pattern. Commented Feb 19, 2020 at 18:50

2 Answers 2

1
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")
Sign up to request clarification or add additional context in comments.

1 Comment

you can do shorter: d = data[i::4]
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.