-2

I have text file which look like this:

textfile

now I want to convert that text file in csv file single row

The outcome would look like: csv_output

zsyfrkn
  • 27
  • 3
  • A text file should read as text and a csv file is also a text file. Please show them as copyable **TEXT** and not as images. – Serge Ballesta Mar 08 '22 at 10:17

4 Answers4

1

You coud zip the splited lines and then ",".join over the sum of the components:

with open("file.txt", "r") as fin,\
     open("file.csv", "w") as fout:
    col1, col2 = zip(*(line.rstrip().split() for line in fin))
    fout.write(",".join(col1 + col2))

If needed, add a "\n" to the end of the row.

If you have much more columns than 2 you could use chain:

from itertools import chain

with open("file.txt", "r") as fin,\
     open("file.csv", "w") as fout:
    zipped = zip(*(line.rstrip().split() for line in fin))
    fout.write(",".join(chain(*zipped)))

Re comment: Use groupby to chop the input into chunks, and then use the procedure above on the chunks:

from itertools import groupby, chain

with open("file.txt", "r") as fin,\
     open("file.csv", "w") as fout:
    for key, group in groupby(fin, key=lambda line: bool(line.strip())):
        if key:
            zipped = zip(*(line.rstrip().split() for line in group))
            fout.write(",".join(chain(*zipped)) + "\n")

Out put for file.txt

dq1    sp1    tq1    rp1
dq2    sp2    tq2    rp2
dp3    sp3    tq3    rp3
dp4    sp4    tq4    rp4

1      2      3      4
5      6      7      8
9      10     11     12
13     14     15     16

in file.csv is

dq1,dq2,dp3,dp4,sp1,sp2,sp3,sp4,tq1,tq2,tq3,tq4,rp1,rp2,rp3,rp4
1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16
Timus
  • 10,974
  • 5
  • 14
  • 28
0

You could use T or transpose() to switch orientation of your DataFrame - Getting rid of headers and index set them to false:

df.T.to_csv('result.csv',header=False, index=False)

Example

import pandas as pd

df = pd.DataFrame(['db1','db2','db3','db4','db5','db6'])

df.T.to_csv('result.csv',header=False, index=False)

Output

db1,db2,db3,db4,db5,db6\r\n
HedgeHog
  • 22,146
  • 4
  • 14
  • 36
0

First we will import pandas:

import pandas as pd

Second we will read the txt.file:

df = pd.read_csv("x.txt")

Third we will make this df -> csv with Transpose (to switch column orientation to row orientation) and header = False (will drop column names row)

df.T.to_csv('result.csv', header=False)
dani99
  • 21
  • 5
0

A csv is also a text file. You could simply read the text file as follows:

with open("in.txt", "r") as f:
    columns = f.read().splitlines()

And write a new one:

with open("out.csv", "w") as out:
    out.write(",".join(columns)) # "," is default, you can use any sep