2017-05-14 211 views
2

我有一个关于将xlsx文件导入Python的基本问题。我已经检查了许多关于同一主题的回复,但是我仍然无法将我的文件导入Python,无论我尝试什么。这里是我的代码和错误我收到:将excel文件导入python

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) 

错误:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\cagdak\\Desktop\\python_self_learning\\Coursera\\sample_data.xlsx' 
+0

你的问题是,该文件是找不到,不是导入问题:验证文件处于您认为处于的位置。 – boardrider

+0

提示:您是否确认该位置存在xlsx文件? – karthikr

+0

是的,它的确如此。我在这里复制文件夹路径:C:\ Users \ cagdak \ Desktop \ python_self_learning \ Coursera和excel文件的名称是:sample_data –

回答

4

随着大熊猫就可以直接获得一个excel文件的列。这是代码。

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

#print the column names 
print df.columns 

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

#get a data frame with selected columns 
FORMAT = ['Col_1', 'Col_2', 'Col_3'] 
df_selected = df[FORMAT] 
+0

谢谢,但我仍然收到“IOError:[Errno 2]没有这样的文件或目录”错误尽管我100%确定文件位置和文件名是正确的。我花了近3个小时来做​​到这一点。 –

0

您应该使用raw strings or escape your backslash代替,例如:

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

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

我已经试过这些,但仍然得到相同的错误... –

+0

@CagdasKanar你有阅读权限的文件吗?如果你运行'python -c“import os; print(os.stat(r'C:\ Users \ cagdak \ Desktop \ python_self_learning \ Coursera \ sample_data.xlsx'))”'?会发生什么? – andy

+0

我应该在笔记本电脑或终端上运行这个吗? –

0

继续前进,尝试这个办法:

file_location = 'C:/Users/cagdak/Desktop/python_self_learning/Coursera/sample_data.xlsx' 
+0

这不提供问题的答案。一旦你有足够的[声誉](https://stackoverflow.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [来自评论](/ review/low-quality-posts/19024737) – Fawzan

+0

在您的代码中添加细节。 –