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

前端 未结 7 961

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

    File I/O neutral solution:

    csv = """12123, 1324, 232324, 243443, 234, 2345
    
    2334, 2445, 22355, 222234, 2345"""  # replace this with the file you read from CSV
    
    def sixPerLineToThreePerLine(s):
      result = ""
      for line in s.split("\n"):
        sp = line.split(", ")
        result = result + ", ".join(sp[:3]) + "\n" + ", ".join(sp[3:])
      return result
    
    print(sixPerLineToThreePerLine(csv))  # replace this with code to write to CSV
    

提交回复
热议问题