How to transform a list into a CSV file with N items per row?

前端 未结 7 955

I want to create a new CSV file with 3 items per row. My source file looks like (there are no new lines / line breaks):

         


        
7条回答
  •  温柔的废话
    2021-01-29 11:44

    What you want to do is read in the data from the file, then split it into individual elements. Once you have it in individual elements you can put them in groups of three and write to your output file.

    Something like this should work:

    def read_data(file_path):
        with open(file_path, 'r') as fh:
            elements = fh.read()
        data = [element.strip() for element in elements.split(',')]
        return data
    
    def group(data):
        grouped = [', '.join(data[n:n+3]) for n in range(0, len(data), 3)]
        return grouped
    
    def write(data, output):
        with open(output, 'w') as fh:
            fh.writelines(data)
    
    def main():
        data = read('test.csv')
        data = group(data)
        write(data, 'test2.csv')
    

提交回复
热议问题