LoginSignup
1
2

More than 3 years have passed since last update.

PythonでSambaサーバーにあるWordファイルを編集する

Last updated at Posted at 2019-05-21

概要

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)
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2