python - 带有枚举的 for 循环迭代 4 次,但只有 1 个数据帧被写入 Excel,而不是 4 个数据帧
问题描述
我整天都在为这段代码苦苦挣扎。在循环的每次运行期间,都会从不同的 MS Word 文件中读取一个表。该表被复制到数据框,然后被复制到 Excel 文件中的一行。
随着 for 循环的每次后续运行,Excel 行会递增,因此可以将新数据帧写入新行,但在文件执行后,只有一行显示数据帧。
当我打印(tfile)时,我得到以下..('CIV-ASCS-016_TRS.docx','CIV-ASCS-018_TRS .docx','CIV-ASCS-020_TRS.docx','CIV-ASCS-021_TRS .docx') 这证明循环基于目录中的 4 个文件运行了 4 次。我在 for 循环之外将初始行 pos 设置为 0。
注意:关于导入必要的库,我没有显示任何代码行。
files = glob('*.docx')
pos = 1
for i, wfile in enumerate(files[:1]):
document = Document(wfile)
table = document.tables[0]
data = []
keys = {}
for j, row in enumerate(table.rows):
text = (cell.text for cell in row.cells)
if j == 0:
keys = tuple(text)
continue
row_data = dict(zip(keys, text))
data.append(row_data)
tfile = tuple(files)
df = pd.DataFrame(data)
df.loc[-1] = [wfile, 'Test Case ID']
df.index = df.index + 1 # shifting index
df = df.sort_index() # sorting by index
df1 = df.rename(index=str, columns={"Test Case ID": "TC Attributes"})
df21 = df1.drop(columns = ['TC Attributes'])
df3 = df21.T
# read the existing sheets so that openpyxl won't create a new one later
book = load_workbook('test.xlsx')
writer = pd.ExcelWriter('test.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df3.to_excel(writer, 'sheet7', header = False, index = False, \
startrow = pos)
pos += 1
writer.save()
解决方案
推荐阅读
- android - 使用 kotlin 进行 Espresso webview 测试
- c# - WPF 不显示垂直滚动条
- salesforce - 用于标准 API 的 Mulesoft 4 Salesforce 集成
- mysql - SQL 在用户输入值上使用 LIKE
- javascript - 如何在不编辑的情况下使用原始数据文件
- ios - 后台监听 AVAudioSession 路由变化
- flutter - 无法在飞镖中映射项目列表(对象引用)
- node.js - Node.js - EventListener - 仅捕获触发数据事件的套接字的关闭事件
- php - 如何替换 URL 中的 GET 参数
- python - SymPy 的多元最小值