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?
Excel is a popular and powerful spreadsheet application for Windows. The openpyxl module allows your Python programs to read and modify Excel spreadsheet files.
If you have a file and you want to parse the data in it, you need to perform the following in this order: import the pandas module. open the spreadsheet file (or workbook) select a sheet.
Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files.
Edit:
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
:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
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) xl.sheet_names >>> [u'Sheet1', u'Sheet2', u'Sheet3'] df = xl.parse("Sheet1") df.head()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With