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

前端 未结 7 960

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:36

    This should help. This was written using python 2.7 so if you have any problems running it in 3.x let me know and I can try to help.

    import csv # import the csv module you will need, if you want to avoid this you can just read it in as a text file
    output = """""" # make an output string
    num = 0 #initialize num that trakcs how many numbers have ben read
    with open('datacsv.csv', 'rb') as f: # open the input file
        file = csv.reader(f) # initialize the file as being a csv file
        for row in file: # for every row (you said no new lines, but just in case)
            for data in row: # for ever entry in the row
                if(num == 2): # if you have read in three numbers
                    num = 0 # reset num
                    output += data + "\n" # output a new line and the current number
                else:
                    num += 1 # increment num
                    output += data + "," # add to output the data and a comma
    
    
    new = open("outputcsv.csv", "w") # create the output file
    new.write(output) # write the output data to the new file
    

提交回复
热议问题