在Python 2.7中,我有很多想要转换为Excel的csv文件。 csv文件的名称是abcd1.csv
,abcd2.csv
等。我想将它们转换为abcd1.xls
,abcd2.xls
等。虽然我能够在一个文件上执行此操作,但我不知道如何在多个文件上执行此操作。
这是我到目前为止使用的功能:
from openpyxl import Workbook
import csv
wb = Workbook()
ws = wb.active
file_name = "COUNT16_DISTRIBUTION" + str(count3*1) + ".csv"
with open(file_name, 'r') as f:
for row in csv.reader(f):
ws.append(row)
wb.save()
file_name可以在while循环中使用,我可以浏览每个csv文件,但我不知道如何将它们保存为.xls
。
这是一个熊猫的例子:
import pandas as pd
import os
# Create function that converts csv 2 excel
def csv2excel(filepath, sep=','):
df = pd.read_csv(filepath, sep=sep)
newpath = os.path.splitext(filepath)[0] + '.xlsx'
df.to_excel(newpath, index=False)
# Loop through files and call the function
for f in os.listdir('.'):
if f.endswith('.csv') and f.startswith('abcd'):
csv2excel(f)