概要
PythonからSambaファイルサーバーに接続し、docxファイルを開き、編集、保存する。
なお、一時ファイルを作らずに作業を行う。
環境
- Ubuntu Server 18.04.2 LTS
- Python 3.6.7
追加パッケージ
- python-docx
- pysmb
コード
import io
import platform
import docx
import smb
from smb.SMBConnection import SMBConnection
conn = SMBConnection(
"username",
"password",
platform.uname().node,
"remote_name",
use_ntlm_v2=True,
)
# ファイルサーバーに接続する
conn.connect("hostname", 139)
root = "/"
filepath = "/hoge.docx"
# 開く
with io.BytesIO() as inputfile:
conn.retrieveFile(root, filepath, inputfile)
doc = docx.Document(inputfile)
# ここで編集操作など
# 保存
with io.BytesIO() as outputfile:
doc.save(outputfile)
outputfile.seek(0)
conn.storeFile(root, filepath, outputfile)