如何使用Python直接从服务器读取Excel文件 [英] How to read an excel file directly from a Server with Python
问题描述
场景::我试图从服务器文件夹中读取一个excel文件,然后将该文件的每个工作表读取到一个数据框中并执行一些操作.
Scenario: I am trying to read a excel file from a server folder and after that read each worksheet of that file into a dataframe and perform some operations.
问题:我尝试了多种方法,但是遇到了不同的情况:要么我读取了文件,但将其视为str,并且无法执行操作,或者无法读取文件.
Issue: I have trying multiple approaches but facing different situations: either I read the file, but it is seen as a str and the operations cannot be performed, or the file is not read.
到目前为止我尝试过的事情:
#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的文档以及SO中的其他一些类似问题,但仍然无法解决此问题.前任: Python-如何从服务器读取路径文件/文件夹 使用Python,如何访问Windows网络上的共享文件夹? https://docs.python.org/release/2.5. 2/tut/node9.html#SECTION009200000000000000000
Obs: I also researched the documentation for reading with pd and some other similar questions in SO, but still could not solve this problem. Ex: 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
问题:实现此目标的正确方法是什么?
Question: What is the proper way to achieve this?
推荐答案
您需要以rb模式打开文件
You need to open the file as rb mode
b =常规文件 r =仅读取文件
b = bynary file r = only read the file
f = open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx', 'rb')
您可以使用熊猫库可以为您完成大部分工作
You can use pandas library that will do most of the work for you
进口大熊猫
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)
在此处
这篇关于如何使用Python直接从服务器读取Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!