【问题标题】:How to automatically name Excel files just generated from csv files with Python如何使用 Python 自动命名刚刚从 csv 文件生成的 Excel 文件
【发布时间】:2022-01-03 09:55:09
【问题描述】:

我需要以自动方式将 csv 文件转换为 Excel 文件。我无法用相应的 csv 文件的名称命名 Excel 文件。 我将 csv 文件保存为“Trials_1”、“Trials_2”、“Trilas_3”,但是使用我编写的 Python 代码给了我一个错误,并要求我提供名为“Trials_4”的 csv 文件。然后,如果我将 csv 文件“Trials_1”重命名为“Trials_4”,程序将运行并生成一个名为“Trials_1”的 Excel 文件。 如何更正我的代码?

'''

import csv

import openpyxl as xl

import os, os.path

directory=r'C:\\Users\\PycharmProjects\\input\\'

folder=r'C:\\Users\\PycharmProjects\\output\\'

for csv_file in os.listdir(directory):

def csv_to_excel(csv_file, excel_file):

    csv_data=[]

    with open(os.path.join(directory, csv_file)) as file_obj:

        reader=csv.reader(file_obj)

        for row in reader:

            csv_data.append(row)

    workbook= xl.Workbook()

    sheet=workbook.active

    for row in csv_data:

        sheet.append(row)

        workbook.save(os.path.join(folder,excel_file))


if __name__=="__main__":
    m = sum(1 for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)))
    new_name = "{}Trial_{}.csv".format(directory, m + 1)
    k = sum(1 for file in os.listdir(folder) if os.path.isfile(os.path.join(folder, file)))
    new_name_e = "{}Trial_{}.xlsx".format(folder, k + 1)
    csv_to_excel(new_name,new_name_e)

'''

谢谢。

【问题讨论】:

    标签: python excel csv


    【解决方案1】:

    您好 Annachiara,欢迎来到 StackOverflow,

    我将只使用 pandas 来修改“csv_to_excel”函数。

    在此之前,您应该安装“xlsxwriter”:

    pip install XlsxWriter
    

    那么函数应该是这样的:

    def csv_to_excel(csv_file,excel_file,csv_sep=';'):
    
        # read the csv file with pandas
        df=pd.read_csv(csv_file,sep=csv_sep)
        # create the excel file
        writer=pd.ExcelWriter(excel_file, engine='xlsxwriter')
        # copy the csv content (df) into the excel file
        df.to_excel(writer,index=False)
        # save the excel file
        writer.save()
        # print what you converted for reference
        print(f'csv file {csv_file} saved as excel in {excel_file}')
    

    只需确保正确读取 csv:我只添加了分隔符参数,但您可能想要添加所有其他参数(如解析日期等)

    然后你可以用for循环转换csv文件列表(我用了更多的步骤让它更清晰)

    dir_in=r'C:\\Users\\PycharmProjects\\input\\'
    
    dir_out=r'C:\\Users\\PycharmProjects\\output\\'
    
    csvs_to_convert=os.listdir(dir_in)
    
    for csv_file_in in csvs_to_convert:
        
        # remove extension from csv files
        file_name_no_extension=os.path.splitext(csv_file_in)[0]
        # add excel extension .xlsx
        excel_name_out=file_name_no_extension+'.xlsx'
        # write names with their directories
        complete_excel_name_out=os.path.join(dir_out,excel_name_out)
        complete_csv_name_in=os.path.join(dir_in,csv_file_in)
        # convert csv file to excel file
        csv_to_excel(complete_csv_name_in,complete_excel_name_out,csv_sep=';')
    

    【讨论】:

    • 非常感谢,我将您的代码的最后一部分添加到我的代码中,现在可以顺利运行了。
    • 伟大的安纳奇亚拉!你能把它标记为接受的答案吗?
    【解决方案2】:

    每个 csv 作为单独的 excel 文件

    import glob
    import pandas as pd
    import os
    
    csv_files = glob.glob('*.csv')
    for filename in csv_files:
        sheet_name = os.path.split(filename)[-1].replace('.csv', '.xlsx')
        df = pd.read_csv(filename)
        df.to_excel(sheet_name, index=False)
    

    不同工作表中同一excel中的所有csv

    import glob
    import pandas as pd
    import os
    
    # Create excel file
    writer = pd.ExcelWriter('all_csv.xlsx')
    
    csv_files = glob.glob('*.csv')
    for filename in csv_files:
        sheet_name = os.path.split(filename)[-1].replace('.csv', '')
        df = pd.read_csv(filename)
        # Append each csv as sheet
        df.to_excel(writer, sheet_name=sheet_name, index=False)
    writer.save()
    

    【讨论】:

      【解决方案3】:

      假设您希望保持代码的相同结构,我只是修复了代码中的一些技术问题以使其正常工作(请将文件夹路径更改为您自己的):

      import csv
      
      import openpyxl as xl
      
      import glob, os, os.path
      
      directory= 'input'
      
      folder= '../output' # Since 'input' would be my cwd, need to step back a directory to reach 'output'
      
      # Using your function, just passing different arguments for convinient.
      def csv_to_excel(f_path, f_name):
      
          csv_data=[]
      
          with open(f_path, 'r') as file_obj:
      
              reader=csv.reader(file_obj)
      
              for row in reader:
      
                  csv_data.append(row)
      
          workbook= xl.Workbook()
      
          sheet=workbook.active
      
          for row in csv_data:
      
              sheet.append(row)
      
              workbook.save(os.path.join(folder, f_name + ".xlsx"))
      
      
      def main():
          os.chdir(directory) # Defining input directory as your cwd
          # Searching for all files with csv extention and sending each to your function
          for file in glob.glob("*.csv"):
              f_path = os.getcwd() + '\\' + file # Saving the absolute path to the file
              f_name = (os.path.splitext(file)[0]) # Saving the name of the file
              csv_to_excel(f_path, f_name) 
      
      if __name__=="__main__":
          main()
      

      附注: 请避免迭代函数的定义,因为您只需要定义一次函数。

      【讨论】:

      • 感谢您的建议,我已将 def 从循环中排除。
      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 2013-08-02
      • 2017-06-12
      • 2017-12-19
      • 1970-01-01
      • 2013-07-16
      • 2023-03-11
      • 2017-12-03
      相关资源
      最近更新 更多