Skip to content

Instantly share code, notes, and snippets.

@tombola
Forked from jrivero/csv_splitter.py
Last active November 8, 2019 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tombola/7d68aa32fb5aceed44166d5a948b196d to your computer and use it in GitHub Desktop.
Save tombola/7d68aa32fb5aceed44166d5a948b196d to your computer and use it in GitHub Desktop.
A Python CSV splitter
import os
def split(filehandler, delimiter=',', row_limit=10000,
output_name_template='output_%s.csv', output_path='.', keep_headers=True, verbose=False):
import csv
reader = csv.reader(filehandler, delimiter=delimiter)
current_piece = 1
current_out_path = os.path.join(
output_path,
output_name_template % current_piece
)
current_out_writer = csv.writer(open(current_out_path, 'w'), delimiter=delimiter)
current_limit = row_limit
if keep_headers:
headers = next(reader)
current_out_writer.writerow(headers)
for i, row in enumerate(reader):
if i + 1 > current_limit:
current_piece += 1
current_limit = row_limit * current_piece
current_out_path = os.path.join(
output_path,
output_name_template % current_piece
)
current_out_writer = csv.writer(open(current_out_path, 'w'), delimiter=delimiter)
if verbose:
print(current_out_path)
if keep_headers:
current_out_writer.writerow(headers)
current_out_writer.writerow(row)
# Example usage
split(open('./metadata.csv', 'r'), row_limit=30, verbose=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment