-
-
Save tombola/7d68aa32fb5aceed44166d5a948b196d to your computer and use it in GitHub Desktop.
A Python CSV splitter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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