How can I open an Excel file in Python?


How do I open a file that is an Excel file for reading in Python?

I've opened text files, for example, sometextfile.txt with the reading command. How do I do that for an Excel file?

8/4/2012 11:29:21 PM

In the newer version of pandas, you can pass the sheet name as a parameter.

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

Check the docs for examples on how to pass sheet_name:

Old version:
you can use pandas package as well....

When you are working with an excel file with multiple sheets, you can use:

import pandas as pd
xl = pd.ExcelFile(path + filename)

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

df = xl.parse("Sheet1")

df.head() will print first 5 rows of your Excel file

If you're working with an Excel file with a single sheet, you can simply use:

import pandas as pd
df = pd.read_excel(path + filename)
print df.head()
5/14/2018 5:11:44 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow