splitting one csv into multiple files in python

前端 未结 10 2096
执念已碎
执念已碎 2020-12-05 07:28

I have a csv file of about 5000 rows in python i want to split it into five files.

I wrote a code for it but it is not working

import codecs
import c         


        
10条回答
  •  情深已故
    2020-12-05 08:00

    In Python

    Use readlines() and writelines() to do that, here is an example:

    >>> csvfile = open('import_1458922827.csv', 'r').readlines()
    >>> filename = 1
    >>> for i in range(len(csvfile)):
    ...     if i % 1000 == 0:
    ...         open(str(filename) + '.csv', 'w+').writelines(csvfile[i:i+1000])
    ...         filename += 1
    

    the output file names will be numbered 1.csv, 2.csv, ... etc.

    From terminal

    FYI, you can do this from the command line using split as follows:

    $ split -l 1000 import_1458922827.csv
    

提交回复
热议问题