如何通过 python 读取同一文件夹中多个 docx 文件中的表格
How to read tables in multiple docx files in a same folder by python
我有一个名为 "Test_Plan" 的文件夹。它由多个docx文件组成,每个docx文件有多个表。我的问题是如何读取整个 docx 文件并给出输出?例如,所有 docx 文件都有多个表格,我选择一个 docx 文件并给出类似
的输出
(即)
桌子总数:52
YES 自动化总数:6
NO 自动化总数:5
像这样,我需要自动处理 "Test_Plan" 文件夹中的所有文件。
希望你能理解我的问题。
我从单个 docx 文件读取表格的代码:
#Module to retrive the word documents
from docx import Document
doc = Document("sample2.docx")
#Reading the tables in the particular docx
i = 0
for t in doc.tables:
for ro in t.rows:
if ro.cells[0].text=="ID" :
i=i+1
print("Total Number of Tables: ", i)
#Counting the values of Automation
# This will count how many yes automation
j=0
for table in doc.tables:
for ro in table.rows:
if ro.cells[0].text=="Automated Test Case" and (ro.cells[2].text=="yes" or ro.cells[2].text=="Yes"):
j=j+1
print("Total Number of YES Automations: ", j)
#This part is used to count the No automation values
k = 0
for t in doc.tables:
for ro in t.rows:
if ro.cells[0].text=="Automated Test Case" and (ro.cells[2].text=="no" or ro.cells[2].text=="No"):
k=k+1
print("Total Number of NO Automations: ", k)
输出:
您可以使用 glob 查找所有文件,例如:
import glob
for name in glob.glob('Test_Plan/*.docx'):
doc = Document(name)
...
glob 将 return 匹配给定模式的文件名列表。您可以遍历该列表,如上面的 for 循环所示,并依次打开每个文件。打开文件后,您只需插入代码即可。
当然,您必须在循环之前初始化您的变量。
为了拆分文件名,我建议使用以下方法:
import os.path
path, filename = os.path.split(input)
我有一个名为 "Test_Plan" 的文件夹。它由多个docx文件组成,每个docx文件有多个表。我的问题是如何读取整个 docx 文件并给出输出?例如,所有 docx 文件都有多个表格,我选择一个 docx 文件并给出类似
的输出(即)
桌子总数:52
YES 自动化总数:6
NO 自动化总数:5
像这样,我需要自动处理 "Test_Plan" 文件夹中的所有文件。 希望你能理解我的问题。
我从单个 docx 文件读取表格的代码:
#Module to retrive the word documents
from docx import Document
doc = Document("sample2.docx")
#Reading the tables in the particular docx
i = 0
for t in doc.tables:
for ro in t.rows:
if ro.cells[0].text=="ID" :
i=i+1
print("Total Number of Tables: ", i)
#Counting the values of Automation
# This will count how many yes automation
j=0
for table in doc.tables:
for ro in table.rows:
if ro.cells[0].text=="Automated Test Case" and (ro.cells[2].text=="yes" or ro.cells[2].text=="Yes"):
j=j+1
print("Total Number of YES Automations: ", j)
#This part is used to count the No automation values
k = 0
for t in doc.tables:
for ro in t.rows:
if ro.cells[0].text=="Automated Test Case" and (ro.cells[2].text=="no" or ro.cells[2].text=="No"):
k=k+1
print("Total Number of NO Automations: ", k)
输出:
您可以使用 glob 查找所有文件,例如:
import glob
for name in glob.glob('Test_Plan/*.docx'):
doc = Document(name)
...
glob 将 return 匹配给定模式的文件名列表。您可以遍历该列表,如上面的 for 循环所示,并依次打开每个文件。打开文件后,您只需插入代码即可。 当然,您必须在循环之前初始化您的变量。
为了拆分文件名,我建议使用以下方法:
import os.path
path, filename = os.path.split(input)