我想通过python获取我公司内我的个人oneDrive/sharepoint中的所有文件列表。但是,我只得到一个空列表作为返回,没有任何错误。
我的代码如下所示(取自Sharepoint_files_python:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.files.file import File
import io
user = 'user'
pw = 'pw'
url = 'https://company-my.sharepoint.com'
rel_url = '/personal/name_company/Documents/further/path/to/folder/'
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(user, pw):
ctx = ClientContext(url, ctx_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print('Authenticated into sharepoint as: ',web.properties['Title'])
else:
print(ctx_auth.get_last_error())
folder = ctx.web.get_folder_by_server_relative_url(rel_url)
fold_names = []
sub_folders = folder.files #Replace files with folders for getting list of folders
ctx.load(sub_folders)
ctx.execute_query()
for s_folder in sub_folders:
fold_names.append(s_folder.properties["Name"])
print(fold_names)
这给出了一个空列表作为输出: []
我尝试在 ctx.web 中访问的其他所有内容也都是空的,例如:
root_folder = ctx.web.default_document_library().root_folder
ctx.load(root_folder,['Files'])
ctx.execute_query()
for f in root_folder.files:
print(f.name)
[]
我的预期结果是: ['file.xlsx','file_35.xlsx',....]
但是,我可以通过以下方式直接访问该文件夹中的各个文件(但这些文件已更新和更改,因此不适合硬编码):
url = 'https://company-my.sharepoint.com/personal/name_company/Documents/further/path/to/folder/file.xlsx'
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(user, pw):
ctx = ClientContext(url, ctx_auth)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Authentication successful")
else:
print(ctx_auth.get_last_error())
resp = File.open_binary(ctx,url)
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(resp.content)
bytes_file_obj.seek(0) #set file object to start
df = pd.read_excel(bytes_file_obj,engine='openpyxl',header=0)
print(df)
我得到了文件被读取并在 python 中可用的预期结果。
有谁知道为什么在执行完整的共享点工作代码时没有错误以及如何检索文件夹中的文件列表?
我不熟悉您尝试使用的 Office365 库,但我可以举一个示例,说明如何使用 SharePlum 来做到这一点:
from shareplum import Site
from shareplum import Office365
from shareplum.site import Version
authcookie = Office365('https://abc.sharepoint.com', username='[email protected]', password='password').GetCookies()
site = Site('https://abc.sharepoint.com/sites/MySharePointSite/', version=Version.v2016, authcookie=authcookie)
rel_url = '/personal/name_company/Documents/further/path/to/folder/'
myfolder = site.Folder(rel_url)
fold_names = []
for f in myfolder.files:
fold_names.append(f["Name"])
print(fold_names)
您可能必须首先将 SharePlum 安装到您的环境中。
请注意,导入 Version 并传递 version=Version.v2016 可能适合也可能不适合您的情况。看起来这个参数是可选的,默认为 Version.v2007。抱歉,但我实际上不确定如何检查您需要哪一个,所以希望这不会引起头痛。