Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing an excel file to python

I have a basic question about importing xlsx files to Python. I have checked many responses about the same topic, however I still cannot import my files to Python whatever I try. Here's my code and the error I receive:

import pandas as pd

import xlrd

file_location = 'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'
workbook = xlrd.open_workbook(file_location)

Error:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\cagdak\\Desktop\\python_self_learning\\Coursera\\sample_data.xlsx'
like image 425
Cagdas Kanar Avatar asked May 14 '17 13:05

Cagdas Kanar


People also ask

Can Python read Excel files?

Excel is a popular and powerful spreadsheet application for Windows. The openpyxl module allows your Python programs to read and modify Excel spreadsheet files.

How do I open a XLSX file in Python?

Run the following command from the terminal to install the required version of xlrd. After completing the installation process, create a python file with the following script to read the sales. xlsx file using the xlrd module. open_workbook() function is used in the script open the xlsx file for reading.


2 Answers

With pandas it is possible to get directly a column of an Excel file. Here is the code.

import pandas
df = pandas.read_excel('sample.xls')

#print the column names
print df.columns

#get the values for a given column
values = df['column_name'].values

#get a data frame with selected columns
FORMAT = ['Col_1', 'Col_2', 'Col_3']
df_selected = df[FORMAT]
like image 169
orbit Avatar answered Oct 01 '22 23:10

orbit


You should use raw strings or escape your backslash instead, for example:

file_location = r'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'

or

file_location = 'C:\\Users\\cagdak\\Desktop\python_self_learning\\Coursera\\sample_data.xlsx'
like image 27
andy Avatar answered Oct 02 '22 00:10

andy