python-3.x - Convert the Powershell script to Python 3
问题描述
I'm trying to perform an upload files from Linux to share point using Python. However I tried a lot by googling but nothing help. At last I got a power shell script that is working. So requesting for help to convert the below script to Python 3
Specify tenant admin and site URL
$User = "justin.jacob@spidersoft.in"
$SiteURL = "https://test-my.sharepoint.com/personal/justin_jacob_spidersoftin";
$Folder = "C:\Users\justin.jacob\Desktop\New folder"
$DocLibName = "Documents"
#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$Password = ConvertTo-SecureString ‘123@123’ -AsPlainText -Force
#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds
#Retrieve list
$List = $Context.Web.Lists.GetByTitle("$DocLibName")
$Context.Load($List)
$Context.ExecuteQuery()
#Upload file
Foreach ($File in (dir $Folder -File))
{
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
}
解决方案
我了解您想将文件上传到共享点,您可以参考以下代码:
import os
from config import config
from shareplum import Site
from shareplum import Office365
from shareplum.site import Version
# get data from configuration
username = config['sp_user']
password = config['sp_password']
authcookie = Office365('https://xxx.sharepoint.com', username=username, password=password).GetCookies()
site = Site('https://xxx.sharepoint.com/sites/abc',version=Version.v365, authcookie=authcookie)
spfolder = site.Folder('Shared Documents/testfolder')
for root, dirs, files in os.walk(r"D:\mytestfolder"):
for file in files:
filepath = os.path.join(root, file)
print(filepath)
# perform the actual upload
with open(filepath, 'rb+') as file_input:
try:
spfolder.upload_file(file_input, file)
except Exception as err:
print("Some error occurred: " + str(err))
该代码使用以下python库:
推荐阅读
- twilio - 我无法使用 Twilio 在 WhatsApp 上获取用户发送的图像
- php - 来自 php 数组字符串的随机编码未在 html 中显示
- c - 如何注意到标准输入重定向到目录
- python - 哪个tensorflow-gpu版本兼容Python 3.7.3
- saml - ADFS 作为与其他依赖方交互的 SAML 服务提供商
- windows - 如何在 Windows 中进行音量提升?
- c# - 使用 C# 通过 TCP 连接两台 PC
- android - 如何在我的活动中实现导航抽屉?
- influxdb - 获取多个标签的最后一个值
- vue.js - vuex:不要在突变之外改变 vuex 存储状态