【问题标题】:Want to generalize the python script for three excel format(.xlsx) / (.xlsm) / (.xls) without doing manually想将python脚本概括为三种excel格式(.xlsx)/(.xlsm)/(.xls)而不做手动
【发布时间】:2021-04-12 08:50:18
【问题描述】:

编写了将每个 excel 表转换为不同 csv 文件的代码。但问题是我编写代码的方式只能适用于一种格式。请参阅此 if else 语句。

if (".xlsx" in str(path_xlsx).lower()) and path_xlsx.is_file():
    xlsx_files = [Path(path_xlsx)]
else:
    xlsx_files = list(Path(path_xlsx).glob("*.xlsx"))  

当前的 if-else 语句仅适用于 .xlsx 文件。但是如果我想为 .xlsm 格式做我需要更改 if-else 语句。

if (".xlsm" in str(path_xlsm).lower()) and path_xlsm.is_file():
    xlsm_files = [Path(path_xlsm)]
else:
    xlsm_files = list(Path(path_xlsm).glob("*.xlsm")) 

我们有什么方法可以调整/自动化此代码,使其适用于这三种 excel 格式(.xls/.xlsm/.xlsx),而无需手动更改不同 excel 格式的代码。

from pathlib import Path
import time
import parser
import argparse
import pandas as pd
import os
import warnings
 
warnings.filterwarnings("ignore")
 
parser = argparse.ArgumentParser(description="Process some integers.")
 
parser.add_argument("path", help="define the directory to folder/file")
parser.add_argument("--verbose", help="display processing information")
 
start = time.time()
 
 
def main(path_xlsx, verbose):
    if (".xlsx" in str(path_xlsx).lower()) and path_xlsx.is_file():
        xlsx_files = [Path(path_xlsx)]
    else:
        xlsx_files = list(Path(path_xlsx).glob("*.xlsx"))    
  
 
    df = pd.DataFrame()
    for fn in xlsx_files:
        all_dfs = pd.read_excel(fn, sheet_name=None)
        for sheet_name, df in all_dfs.items():
            df = df.assign(DataSource=Path(fn.name))
            x=os.path.splitext(fn.name)[0]
            path=r'Output'
            df.to_csv(os.path.join(path,f'{sheet_name}+{x}.csv'),index=False)            
         
if __name__ == "__main__":
    start = time.time()
    args = parser.parse_args()
    path = Path(args.path)
    verbose = args.verbose
    main(path, verbose)  #Calling Main Function
    print("Processed time:", time.time() - start)  #Total Time

记住:我通过批处理脚本运行此代码,因此文件夹中的任何 excel 文件格式都应转换为不同的 excel .csv 文件。在一个文件夹中存在 5 到 6 个文件,其中存在三个 excel 扩展名 (.xlsx/.xlsm/.xls)。

【问题讨论】:

    标签: python excel if-statement


    【解决方案1】:

    我不完全清楚你的问题是什么。下面将迭代所有三种类型的 Excel 文件。我假设pandas 可以毫无问题地处理每种类型的转换。例如,如果您同时拥有具有相同工作表名称的 file.xlsx 和 file.xlsm,我想它们都会转换为相同的 csv 文件名,其中一个覆盖另一个。如果存在这种可能性,您应该能够找到一种处理方法。

    from itertools import chain
    import re
    ​
    ​
    if re.search(r"\.xls[xm]?$", str(path_xlsx).lower()) and path_xlsx.is_file():
        xlsx_files = [Path(path_xlsx)]
    else:
        xlsx_files = list(chain(Path(path_xlsx).glob("*.xls"), Path(path_xlsx).glob("*.xlsx"), Path(path_xlsx).glob("*.xlsm")))
    

    注意

    但实际上没有必要首先将xlsx_files 转换为list,因为您将使用for fn in xlsx_files: 迭代chain(或原始代码中的glob)的结果。既浪费时间又浪费空间。所以:

    from itertools import chain
    import re
    
    
    if re.search(r"\.xls[xm]?$", str(path_xlsx).lower()) and path_xlsx.is_file():
        xlsx_files = [Path(path_xlsx)]
    else:
        xlsx_files = chain(Path(path_xlsx).glob("*.xls"), Path(path_xlsx).glob("*.xlsx"), Path(path_xlsx).glob("*.xlsm"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2013-01-25
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多