[英]How to read tables in multiple docx files in a same folder by python
我有一個名為“Test_Plan”的文件夾。 它由多個 docx 文件組成,每個 docx 文件有多個表。 我的問題是如何讀取整個 docx 文件並給出輸出? 例如,所有 docx 文件都有多個表,我選擇一個 docx 文件並給出如下輸出
(IE)
桌子總數: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 將返回與給定模式匹配的文件名列表。 您可以遍歷該列表,如上面的 for 循環所示,依次打開每個文件。 打開文件后,您只需插入代碼即可。 當然,您必須在循環之前初始化變量。
對於拆分文件名,我建議使用以下方法:
import os.path
path, filename = os.path.split(input)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.