Python 中的 EXCEL 函数 CSV

Function CSV to EXCEL in Python

我想将 csv 文档转换成 excel。 我还希望它是一个使用文档路径的函数。 我知道我必须使用下面的代码,但这不是一个函数。 如果可以,请帮助我。

根据我的理解,问题中没有任何代码(目前),我认为这应该可行:

def csv_to_excel(source_path, source_file, target_path, target_file):
    """ Take the path of a csv file, convert it to excel and save it"""
    import pandas as pd
    import os
    try:
        df = pd.read_csv(os.path.join(source_path, source_file))
        df.to_excel(os.path.join(target_path, target_file), index=False)
        return True
    except Exception as e:
        print(e)
        return False

导入可以(而且通常应该)在主范围内进行。有不明白的地方欢迎留言。