如图,想将这两个文件合并并保存在桌面的话,下面这段代码要怎么改?
import os
import pandas as pd
import time
LOAD_DIR = "/Users/liyi/Downloads/2.22-3.23Python" #设置需要合并文件的路径
def read_csv_or_xlsx(file):
"""
利用pandas 读取csv或者xlsx
:return: DataFrame pandas特有数据结构 ,数据框
"""
if file.endswith(".csv"):
sheet_name = file[:-4]
data_frame = pd.read_csv(os.path.join(LOAD_DIR, file))
else:
# xlsx文件
sheet_name = file[:-5]
data_frame = pd.read_excel(os.path.join(LOAD_DIR), file)
return data_frame, sheet_name
def main():
output_file = "/Users/liyi/total.xlsx" # 合并后生成的文件路径和名称
writer = pd.ExcelWriter(output_file, engine='openpyxl') #通过 openpyxl实现对excel的读写
files = os.listdir(LOAD_DIR)
files.sort() # 自动排序
for file in files:
if os.path.isfile(os.path.join(LOAD_DIR, file)):
if file.endswith(".csv") or file.endswith(".xlsx"):
item_start = time.time()
data_frame, sheet_name = read_csv_or_xlsx(file)
data_frame.to_excel(excel_writer=writer, sheet_name=sheet_name, index=None)
writer.save()
writer.close()
if __name__ == '__main__':
main()