How to save large set of rows and columns from .xlsx output in a file

48 views Asked by At

I have a .xlsx file with large set of rows and columns, and I would like to save the desired output in .csv or .txt file.

import pandas as pd
 
def foo():
    data = pd.read_excel('file/path/filename.xlsx')
    print(data)

    f = open('Output.txt', 'w')
    print(data.head(50),file = f)
    f.close()

I get the Output.txt as

Col1 Col2 ... Col99
1     1   ... 2
2     4   ... 3
.     .   ... .  
.     .   ... . 
4     2   ... 3

instead of all the rows and columns. I realize that I'm just saving whats been printed on screen, can anyone suggest how to save such columns and rows completely in a .csv or .txt?

2

There are 2 answers

1
3dSpatialUser On
data.to_csv('path_to_csv')

Did you try this already?

import pandas as pd
 
def foo():
    data = pd.read_excel('file/path/filename.xlsx')
    data.to_csv('path_to_csv', index=False)
0
Timeless On

Looks like you want to_string (which by default prints every piece of your DataFrame as it is):

def foo():
    data = pd.read_excel('file.xlsx')
    # print(data)

    with open('Output.txt', 'w') as f:
        data.head(50).to_string(f, index=False)