目标:要构建一个python脚本,该脚本将从SharePoint文档库下载所有文件并存储在相同的文件夹结构中(包括第N个子文件夹)
使用:Python 3.6和@Vadim Gremyachev的出色SharePoint REST API tool
完成到现在:
a)检索根目录中的文件夹列表
b)检索给定文件夹中的文件和文件夹列表
c)从给定文件夹迭代下载文件
我不是递归逻辑方面的专家,因此需要一些帮助来解决此问题。
示例代码:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.file import File
from time import time
def print_folder_contents(ctx, folder_name):
try:
folder = ctx.web.get_folder_by_server_relative_url("/sites/abc/Shared Documents/"+folder_name+"/")
ctx.load(folder)
ctx.execute_query()
# Folders
fold_names = []
sub_folders = folder.folders
ctx.load(sub_folders)
ctx.execute_query()
for s_folder in sub_folders:
# print("Folder name: {0}".format(folder.properties["Name"]))
fold_names.append(s_folder.properties["Name"])
# Files
f_names = []
files = folder.files
ctx.load(files)
ctx.execute_query()
for myfile in files:
# print("File name: {0}".format(myfile.properties["Name"]))
f_names.append(myfile.properties["Name"])
return fold_names, f_names
except Exception as e:
print('Problem printing out library contents: ', e)
def print_root_contents(ctx):
try:
list_object = ctx.web.lists.get_by_title('Documents')
folder = list_object.root_folder
ctx.load(folder)
ctx.execute_query()
folders = folder.folders
ctx.load(folders)
ctx.execute_query()
for myfolder in folders:
print("For Folder : {0}".format(myfolder.properties["Name"]))
folder_list, files_list = print_folder_contents(ctx) # , myfolder.properties["Name"])
print("Sub folders - ", folder_list)
print("Files - ", files_list)
except Exception as e:
print('Problem printing out library contents: ', e)
ctx = None
folder_name = 'alpha_test'
url = 'https://company.sharepoint.com/sites/abc'
ctx_auth = AuthenticationContext(url=url)
if ctx_auth.acquire_token_for_user(username='id', password='pass'):
ctx = ClientContext(url, ctx_auth)
print_root_contents(ctx)
上面的代码可以完美地列出所有根目录文件夹以及一个目录内部子文件夹和文件列表。我需要一个表示目录结构的JSON(Python字典)。
python dict的示例(fi:文件,fo:文件夹):
例如:1
{
"root": [
{
"fo1": [
"fi1",
"fi2"
],
"fo2": [
"fi1",
"fi2"
]
},
"fi1",
"fi2"
]
}
例如:2
{
"root": [
{
"fo1": {
"fo1": "f1",
"fo2": [
"f1",
"f2"
]
},
"fo2": [
"fi1",
"fi2"
]
},
"fi1",
"fi2"
]
}