batch process text to csv using python

后端 未结 1 465
日久生厌
日久生厌 2020-12-30 18:14

I need some help with converting a number of text files to csv files. All my text files are in one folder and I want to convert them to csv files into another folder. The na

相关标签:
1条回答
  • 2020-12-30 18:40

    glob.glob() is perfectly suited for the task. Also, use with context manager when working with files:

    import csv
    import glob
    import os
    
    directory = raw_input("INPUT Folder:")
    output = raw_input("OUTPUT Folder:")
    
    txt_files = os.path.join(directory, '*.txt')
    
    for txt_file in glob.glob(txt_files):
        with open(txt_file, "rb") as input_file:
            in_txt = csv.reader(input_file, delimiter='=')
            filename = os.path.splitext(os.path.basename(txt_file))[0] + '.csv'
    
            with open(os.path.join(output, filename), 'wb') as output_file:
                out_csv = csv.writer(output_file)
                out_csv.writerows(in_txt)
    
    0 讨论(0)
提交回复
热议问题