首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用python对.docx进行一些操作

使用python对.docx进行一些操作
EN

Stack Overflow用户
提问于 2017-10-31 20:14:54
回答 1查看 382关注 0票数 0

我已经创建了一个脚本,用于从用户获取路径名并执行一些.docx操作。当我运行脚本时,它给出了该文件夹中.docx的总数,但它不适用于表计数。我不知道我在tkinter中使用了正确的代码。我已经尝试过路径库os.path,但是它不起作用。

这是我的代码:

代码语言:javascript
复制
    import os
    import glob
    import os.path
    from docx import Document

    from tkinter import *
    def print_input():

#To print how many files with .docx extension in the folder 

        mypath = text_entry.get()
        files=0
        for name in os.listdir(mypath):
            if name.endswith('.docx'):
              files=files+1
        print("Total No of Files:",files)

        #To read the .docx and print how many tables in that 

        table=0
        for name in glob.glob('/*.docx'):
          doc=Document(name)
          for t in doc.tables:
            for ro in t.rows:
             if ro.cells[0].text=="ID" :
                table=table+1
          print("Total Number of Tables: ", table)

    root = Tk()
    Label(root, text="Enter Path").grid(row=0)

    text_entry = Entry(root)
    text_entry.grid(row=1, column=0)
    text_entry.config(background="yellow", foreground="blue")
    Button(root, text='Submit', command=print_input).grid(row=3, column=0, sticky=W, pady=4)
    mainloop()

当我试图在glob中指定路径名时,它正在工作,但是当我试图从textbox传递值时,它不是在执行,而是给出正确的细节,它显示随机数字。希望你能理解我的问题

EN

回答 1

Stack Overflow用户

发布于 2017-10-31 20:45:17

不知道“不工作”是什么意思,但是你从"mypath“中得到了名字

代码语言:javascript
复制
for name in os.listdir(mypath):

但是表格来自/*..docx

代码语言:javascript
复制
for name in glob.glob('/*.docx'):

在一次操作中执行(并查看filedialog.askdirectory)

代码语言:javascript
复制
    mypath = text_entry.get()
    files=0
    for name in os.listdir(mypath):
        if name.endswith('.docx'):
          files=files+1
    #print("Total No of Files:",files)

    #To read the .docx and print how many tables in that 

          table=0
    ##for name in glob.glob('/*.docx'):
          doc=Document(name)
          for t in doc.tables:
              for ro in t.rows:
                  if ro.cells[0].text=="ID" :
                      table=table+1
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47043834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档