V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wantyourkiss
V2EX  ›  Python

求助各位大大,怎么用 Python 调用 word 来打开 docx 的文档

  •  
  •   wantyourkiss · 2022-01-04 15:30:13 +08:00 · 1972 次点击
    这是一个创建于 814 天前的主题,其中的信息可能已经有所发展或是发生改变。

    C 盘根目录下有个 xx.docx 文件,怎么用 python 调用 word 来打开这个文件啊?

    10 条回复    2022-01-05 19:21:31 +08:00
    czwstc
        1
    czwstc  
       2022-01-04 15:33:02 +08:00 via iPhone
    你想用 word 打开,就用 python 跑 cmd call word 打开文档
    wangtian2020
        2
    wangtian2020  
       2022-01-04 16:48:20 +08:00
    像 nodejs 的话有个叫 'open'的包,可以调用代码打开文件
    https://www.npmjs.com/package/open

    Python 中肯定也有类似的
    Thresh
        3
    Thresh  
       2022-01-04 16:49:30 +08:00
    os.system() ????
    xingshu1990
        4
    xingshu1990  
       2022-01-04 16:56:02 +08:00
    作为一个浅尝辄止的 me ,不可能是直接上代码的.
    我是先在百度或者谷歌输入:python word docx
    这样至少能知道用什么模块去处理 word 。发现了 python-docx 这个模块
    然后再搜索一下 Python 打开 docx ,有其他搜索结果,我选择了 https://www.jb51.net/article/180546.htm 进行打开。
    发现打开 docx 是这样的代码
    import docx
    file=docx.Document(r"C:\xx.docx")
    dicc
        5
    dicc  
       2022-01-04 17:32:12 +08:00
    @Thresh 正解。os.system(‘xxx.docx’)
    ysc3839
        6
    ysc3839  
       2022-01-04 17:39:41 +08:00
    如果这个文件的完整路径是写死的,那大概可以偷懒用 os.system 。
    如果文件路径不固定,个人不建议用 os.system 或者其他用到了 shell (cmd) 的方案,因为坑比较多,一不小心就可能遇到 shell 注入的问题。
    正确做法有两个,一个是用 ShellExecute 打开,这样会使用文件类型关联的程序打开,不一定是 Word 。
    另一个是想办法找到 Word 的可执行文件路径,启动 Word 并把文件路径通过参数传递过去。
    ClericPy
        7
    ClericPy  
       2022-01-04 21:25:48 +08:00
    怎么没有人提 os.startfile 呢...
    hjue
        8
    hjue  
       2022-01-05 10:32:13 +08:00
    python 打开 word 完全没问题 https://python-docx.readthedocs.io/
    wantyourkiss
        9
    wantyourkiss  
    OP
       2022-01-05 19:19:45 +08:00
    @hjue
    @xingshu1990
    @wangtian2020 开始我是想做一个预览,类似 mac 下按空格键那种,发现并没有很好的实现方式。我只想看一下文档是否是对的,需要看格式和图片是不是对的
    wantyourkiss
        10
    wantyourkiss  
    OP
       2022-01-05 19:21:31 +08:00
    @ClericPy
    @ysc3839
    @dicc
    @Thresh
    @czwstc 对的,直接 os.system(start xxx.docx)就行了,还不会阻塞主线程。 开始我是想做一个预览,类似 mac 下按空格键那种,发现并没有很好的实现方式。我只想看一下文档是否是对的,需要看格式和图片是不是对的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2855 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:22 · PVG 23:22 · LAX 08:22 · JFK 11:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.