I have text file which look like this:
now I want to convert that text file in csv file single row
The outcome would look like: csv_output
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
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