使用 python 获取共享点目录中的文件列表

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

我有一个共享点目录(内联网)的 url,并且需要一个 api 来返回给定 url 的该目录中的文件列表。我怎样才能使用Python做到这一点?

python-2.7 rest sharepoint-2013
4个回答
22
投票

发布以防其他人遇到仅从文件夹路径从 SharePoint 文件夹获取文件的问题。 这个链接确实帮助我做到了这一点:https://github.com/vgrem/Office365-REST-Python-Client/issues/98。我发现了很多关于在 HTTP 中执行此操作的信息,但在 Python 中却没有,所以希望其他人需要更多的 Python 参考。 我假设您已通过 Sharepoint API 设置了 client_id 和 client_secret。如果没有,您可以参考以下内容:https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs

我基本上想获取文件夹中文件的名称/相对 URL,然后获取文件夹中的最新文件并将其放入数据框中。 我确信这不是“Pythonic”的方式来做到这一点,但它有效,这对我来说已经足够好了。

!pip install Office365-REST-Python-Client
from office365.runtime.auth.client_credential import ClientCredential
from office365.runtime.client_request_exception import ClientRequestException
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import io
import datetime
import pandas as pd


sp_site = 'https://<org>.sharepoint.com/sites/<my_site>/'
relative_url = "/sites/<my_site/Shared Documents/<folder>/<sub_folder>"
client_credentials = ClientCredential(credentials['client_id'], credentials['client_secret'])
ctx = ClientContext(sp_site).with_credentials(client_credentials)
libraryRoot = ctx.web.get_folder_by_server_relative_path(relative_url)
ctx.load(libraryRoot)
ctx.execute_query()

#if you want to get the folders within <sub_folder> 
folders = libraryRoot.folders
ctx.load(folders)
ctx.execute_query()
for myfolder in folders:
    print("Folder name: {0}".format(myfolder.properties["ServerRelativeUrl"]))

#if you want to get the files in the folder        
files = libraryRoot.files
ctx.load(files)
ctx.execute_query()

#create a dataframe of the important file properties for me for each file in the folder
df_files = pd.DataFrame(columns = ['Name', 'ServerRelativeUrl', 'TimeLastModified', 'ModTime'])
for myfile in files:
    #use mod_time to get in better date format
    mod_time = datetime.datetime.strptime(myfile.properties['TimeLastModified'], '%Y-%m-%dT%H:%M:%SZ')  
    #create a dict of all of the info to add into dataframe and then append to dataframe
    my_dict = {'Name': myfile.properties['Name'], 'ServerRelativeUrl': myfile.properties['ServerRelativeUrl'], 'TimeLastModified': myfile.properties['TimeLastModified'], 'ModTime': mod_time}
    df_files = df_files.append(my_dict, ignore_index= True )

    #print statements if needed
    # print("File name: {0}".format(myfile.properties["Name"]))
    # print("File link: {0}".format(myfile.properties["ServerRelativeUrl"]))
    # print("File last modified: {0}".format(myfile.properties["TimeLastModified"]))
#get index of the most recently modified file and the ServerRelativeUrl associated with that index
newest_index = df_files['ModTime'].idxmax()
newest_file_url = df_files.iloc[newest_index]['ServerRelativeUrl']

# Get Excel File by newest_file_url identified above
response= File.open_binary(ctx, newest_file_url)
    # save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0)  # set file object to start
    # load Excel file from BytesIO stream
df = pd.read_excel(bytes_file_obj, sheet_name='Sheet1', header= 0)

这是您可以查看的文件属性的另一个有用链接:https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-rest-reference/dn450841(v=office.15 )。向下滚动到文件属性部分。

希望这对某人有帮助。再说一次,我不是专业人士,大多数时候我需要把事情写得更明确一些。也许其他人也有这样的感觉。


0
投票

我有一个共享点目录的网址

假设您询问一个库,您可以使用 SharePoint 的 REST API 并进行 Web 服务调用:

https://yourServer/sites/yourSite/_api/web/lists/getbytitle('Documents')/items?$select=Title

这将返回文档列表:https://yourServer/sites/yourSite/Documents

请参阅:https://msdn.microsoft.com/en-us/library/office/dn531433.aspx

您当然需要适当的权限/凭据才能访问该库。


0
投票

您需要在这里做两件事。

  1. 获取文件列表(可以是目录或简单文件) 您感兴趣的目录。
  2. 遍历此文件列表中的每个项目并检查是否 该项目是一个文件或目录。对于每个目录执行相同的操作 步骤 1 和 2。

您可以在 https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest#working-with- 找到更多文档通过使用休息将文件附加到列表项目

def getFilesList(directoryName):
    ...
    return filesList

# This will tell you if the item is a file or a directory.
def isDirectory(item):
    ...
    return true/false

希望这有帮助。


0
投票

您不能使用“服务器名称/站点/文件夹名称/子文件夹名称/_api/web/lists/getbytitle('Documents')/items?$select=Title”作为 SharePoint REST API 中的 URL。

URL 结构应如下所示,考虑到 WebSiteURL 是包含您尝试从中获取文件的文档库的站点/子站点的 URL,而 Documents 是文档库的显示名称:

WebSiteURL/_api/web/lists/getbytitle('Documents')/items?$select=Title

如果您想列出元数据字段值,您应该在 $select 中添加以逗号分隔的字段名称。

快速提示:如果您不确定 REST API URL 的构成。尝试将 URL 粘贴到 Chrome 浏览器中(您必须使用适当的权限登录到 SharePoint 网站),看看是否获得正确的 XML 格式的结果,如果成功,则更新 REST URL 并运行代码。这样你就可以节省运行 python 代码的时间。

© www.soinside.com 2019 - 2024. All rights reserved.