[英]Python, how to combine different excel workbooks into one excel workbook as sheets
[英]Joining sheets from different excel files into one workbook python
我試圖理解不久前發布的代碼。 我找不到合適的解釋,所以我發了這個帖子。 我是 python 的新手,如果有人能解釋我它是如何工作的,我會非常感激。 我已經標記了我不明白的部分。
代碼本身:
from pandas import ExcelWriter
import glob
import os
import pandas as pd
writer = ExcelWriter("output.xlsx")
for filename in glob.glob("*.xlsx"):
excel_file = pd.ExcelFile(filename)
(_, f_name) = os.path.split(filename) <---
(f_short_name, _) = os.path.splitext(f_name)
for sheet_name in excel_file.sheet_names:
df_excel = pd.read_excel(filename, sheet_name=sheet_name)
df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False) <---
writer.save()
您標記的只是創建者嘗試在新的 excel 文件中命名工作表。
(_, f_name) = os.path.split(filename)
# _: 'C:\\Desktop'
#f_name: 'file.xlsx'
它返回目錄的頭部和尾部。 在這種情況下,尾部是文件名。
df_excel.to_excel(writer, f_short_name+'_'+sheet_name, index=False)
這是將數據框保存到 excel 文件。 第一個論點:
ExcelWriter
如果你想創建一個里面有多個工作表的 excel 文件。file path
(您想在哪里保存它)。 第二個參數:每個數據框的工作Sheet name
。
最后一個參數: index
或行名
了解更多信息:
os.path.split
: https://www.geeksforgeeks.org/python-os-path-split-method/
.to_excel
: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.