Suman Tiwari
Suman Tiwari

Reputation: 40

How to Read Text file as input and write into excel columns using panda?

I am using permission.txt file as intput and want to write data into columns of excel -2007(I am using panda XlsxWriter becasue I want more than 256 columns). I want to write like this into excel file. I have tried following code up to this which writes data in rows instead I want to write data into columns(column 1,column 2......column 400).

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import numpy as np


data = pd.read_csv('F:/Research_Work/python/Permission.txt', sep=" ", header=None)
writer = ExcelWriter('Example2.xlsx')
data.to_excel(writer,'Sheet1',index=False)

Upvotes: 0

Views: 3718

Answers (1)

jmcnamara
jmcnamara

Reputation: 41584

You could just transpose the dataframe data, like this:

import pandas as pd

# Create a Pandas dataframe from some data.
df1 = pd.DataFrame({'Data': [10, 20, 30, 40]})
df2 = df1.T

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Write the data in column and transposed (row) directions.
df1.to_excel(writer, sheet_name='Sheet1', 
             startrow=1, startcol=1, header=False, index=False)

df2.to_excel(writer, sheet_name='Sheet1', 
             startrow=1, startcol=3, header=False, index=False)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Output:

enter image description here

Upvotes: 1

Related Questions