Combine a folder of text files into a CSV with each content in a cell

前端 未结 3 1028
感动是毒
感动是毒 2020-12-20 01:22

I have a folder containing several thousand .txt files. I\'d like to combine them in a big .csv according to the following model:

I found a R script suppose

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 01:35

    The following python script works for me (where path_of_directory is replace by the path of the directory your files are in and output_file.csv is the path of the file you want to create/overwrite):

    #! /usr/bin/python
    
    import os
    import csv
    
    dirpath = 'path_of_directory'
    output = 'output_file.csv'
    with open(output, 'w') as outfile:
        csvout = csv.writer(outfile)
        csvout.writerow(['FileName', 'Content'])
    
        files = os.listdir(dirpath)
    
        for filename in files:
            with open(dirpath + '/' + filename) as afile:
                csvout.writerow([filename, afile.read()])
                afile.close()
    
        outfile.close()
    

    Note that this assumes everything in the directory is a file.

提交回复
热议问题