2017-08-17 135 views
0

方案:我想读从服务器文件夹中的Excel文件,之后读取该文件的每个工作表到一个数据帧,并执行一些操作。如何直接从服务器与Python读取Excel文件

问题:我已经尝试多种方法,但面对不同的情况:要么我读的文件,但它被视为一个STR和不能执行的操作,或文件没有被读取。

我试了一下,到目前为止:

#first attempt 
os.path(r'\\X\str\Db\C\Source\selection\Date\Test','r') 

#second attempt 
directory = os.getcwd() + "\\C\\Source\\selection\\Date\\Test" 

#third attempt 
f = os.getcwd() + "\\C\\Source\\selection\\Date\\Test\\12.xlsx" 

#fourth attempt 
f = open(r'\\X\str\Db\C\Source\selection\Date\Test\12.xlsx', 'r') 

db1 = pd.DataFrame() 
db2 = pd.DataFrame() 
db3 = pd.DataFrame() 
bte = pd.DataFrame() 
fnl = pd.DataFrame() 

wb = load_workbook(f) 

for sheet in wb.worksheets: 

    if sheet.title == "db1": 

     db1 = pd.read_excel(f, "db1") 

观测数据:我也研究了文档与PD和SO其他一些类似的问题阅读,但还是没能解决这个问题。例如: Python - how to read path file/folder from server Using Python, how can I access a shared folder on windows network? https://docs.python.org/release/2.5.2/tut/node9.html#SECTION009200000000000000000

问题:什么是实现这一目标的正确方法?

回答

1

您需要打开该文件作为RB模式

B = bynary文件 R =只读文件

f = open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx', 'rb') 

您可以使用pandas library将完成大部分的工作,为您

进口大熊猫

import pandas 
f = pandas.read_excel(open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx','rb'), sheetname='Sheet 1') 
# or using sheet index starting 0 
f = pandas.read_excel(open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx','rb'), sheetname=2) 

有一个类似的问题here

+1

第二部分完美地工作。我不必将工作簿重新加载到变量中。非常感谢。 – DGMS89

0

From here.

尝试使用在你的UNC路径斜杠:

f = open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx', 'rb') 
+0

感谢您的回答。我刚刚尝试过,它会产生一个新的错误:OSError:文件对象必须以二进制模式打开。 – DGMS89

+0

使用f = open('// X/str/Db/C/Source/selection/Date/Test/12.xlsx','rb')。 xls不是文本文件,是一个辅助文件。 https://docs.python.org/2/library/functions.html#open –

0

我有同样的问题。尝试熊猫和斜杠

pd.read_excel('//X/str/Db/C/Source/selection/Date/Test/12.xlsx') 

拥有完美运行