如何使用Python直接从服务器读取excel文件

问题描述 投票:0回答:3

场景:我正在尝试从服务器文件夹中读取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")

Obs:我还研究了用pd阅读文档和其他一些类似的问题,但仍然无法解决这个问题。例如: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

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

python pandas os.path
3个回答
1
投票

您需要将文件作为rb模式打开

b =二进制文件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
投票

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

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

必须完美地工作


0
投票

From here.

尝试在UNC路径中使用正斜杠:

f = open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx', 'rb')
© www.soinside.com 2019 - 2024. All rights reserved.