首页 > 解决方案 > 使用python将大型xlsx拆分为多个csv文件

问题描述

我正在尝试通过使用 pandas 拆分单个大 xls 文件来生成多个 csv 文件,但只生成一个小文件,不会生成其余文件。请找到以下示例函数。

def xls_split_to_csv(sourceFilePath):
curr_date = datetime.now().strftime("%d-%m-%Y")
curr_time = datetime.now().strftime("%H-%M-%S")
try:
    logMessage("--------------------------------------------------------")
    logMessage(f'######### Split engine started - {curr_date}  ##########')
    logMessage("--------------------------------------------------------")
    chunk_size = config_params['split_size']
    batch = 0
    df = pd.read_excel(sourceFilePath)
    o_filename = f'file_{curr_date}_{curr_time}_{batch + 1}.csv'
    file_count = math.ceil(len(df) / chunk_size)
    for chunk in np.array_split(df, file_count):
        logMessage(f'Splitting file ----> ({batch + 1} of {file_count})')
        output_path = os.path.join('../TruncatedFile', o_filename)
        chunk.to_csv(output_path, index=False, header=True)
        batch += 1

except ZeroDivisionError as zeroEx:
    logError("Exception: ")
except Exception as ex:
    logError("Exception: ")

标签: pythonpandasdataframenumpy

解决方案


移动线

o_filename = f'file_{curr_date}_{curr_time}_{batch + 1}.csv'

进入你的for循环;目前您永远不会更改输出文件名。


推荐阅读