大家好,我还在学习python 3,我对VBA比较熟悉。我有下面的python代码,它的作用是对csv文件进行排序并将转换保存在新文件中。目前我可以在闲置运行它,它的工作原理。我需要能够将其定义为函数,以便我可以从vba按钮调用它。
from xlwings import Workbook, Range
# file group_by_trailing_py2.py
import os
import csv
from itertools import groupby
DELIM=';'
IN_FILENAME = 'My Product.csv'
OUT_FILENAME = 'My Product.grouped.csv'
keyfunc = lambda row: row[1:]
with open(IN_FILENAME) as csv_file:
``rows = sorted(csv.reader(csv_file, delimiter=DELIM), key=keyfunc)
it = map(lambda t: [", ".join(v[0].strip() for v in t[1]) + " "] + t[0],
groupby(rows, key=keyfunc))
with open(OUT_FILENAME, 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=DELIM)
for row in it:
writer.writerow(row)
答案 0 :(得分:1)
def f():
DELIM=';'
IN_FILENAME = 'My Product.csv'
OUT_FILENAME = 'My Product.grouped.csv'
keyfunc = lambda row: row[1:]
with open(IN_FILENAME) as csv_file:
``rows = sorted(csv.reader(csv_file, delimiter=DELIM), key=keyfunc)
it = map(lambda t: [", ".join(v[0].strip() for v in t[1]) + " "] + t[0],
groupby(rows, key=keyfunc))
with open(OUT_FILENAME, 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=DELIM)
for row in it:
writer.writerow(row)
f()