大家好,我仍在学习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)

最佳答案

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()

09-11 20:00