Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (12.7k points)

I know how to open textfiles, but I don't know how to open an excel file. Can anyone help me to sort out my doubt?

1 Answer

0 votes
by (26.4k points)

New Version

Try the following code in the case of new version of python.

file_name =  # path to file + file name

sheet =  # sheet name or sheet number or list of sheet numbers and names

import pandas as pd

df = pd.read_excel(io=file_name, sheet_name=sheet)

print(df.head(5))  # print first 5 rows of the dataframe

You can also pass name of the sheet as parameter.

Older version:

You can use the following code, when you're working with multiple sheets in an excel file.

import pandas as pd

xl = pd.ExcelFile(path + filename)

xl.sheet_names

>>> [u'Sheet1', u'Sheet2', u'Sheet3']

df = xl.parse("Sheet1")

df.head()

whereas, df.head() will return the first 5 records of the excel sheet.

Incase, if you're working with a single sheet:

import pandas as pd

df = pd.read_excel(path + filename)

print df.head()

Interested to learn python? Come and Join our python course

Related questions

0 votes
1 answer
asked Jul 30, 2019 by Rajesh Malhotra (19.9k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...