【问题标题】:To do some operation with .docx by using python tkinter使用 python tkinter 对 .docx 进行一些操作
【发布时间】:2017-10-31 20:14:54
【问题描述】:

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

这是我的代码:

    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 中指定路径名时,它正在工作,但是当我尝试从文本框中传递值时,它没有执行而不是提供正确的详细信息,它显示随机数。希望你能理解我的问题

【问题讨论】:

  • for name in glob.glob(mypath+'/*.docx'): 也应该可以工作
  • 你能举一个它显示的随机数的例子吗?
  • @PRMoureu 你拯救了我的一天。非常感谢

标签: python-3.x tkinter filepath docx glob


【解决方案1】:

不知道“不起作用”是什么意思,但是您从“mypath”中获取名称

for name in os.listdir(mypath):

但是表格来自 '/*.docx'

for name in glob.glob('/*.docx'):

在一个操作中完成(并查看 filedialog.askdirectory)

    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

【讨论】:

  • 当我尝试将其作为一个操作时,我发现错误:“在 '%s' 处找不到包” % pkg_file docx.opc.exceptions.PackageNotFoundError: 在'third.docx 处找不到包'
  • 你能编辑你的完整代码吗? @Curly 乔
  • 再次,我不知道“当我尝试将其作为一个操作时,我发现错误:”是什么意思或它指的是哪一行。您可能必须提供文件的完整路径,以便将 os.path.join(mypath, name) 提供给 Document()。也打印它以确保它去你想去的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2012-02-18
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多