|
| 1 | +import os |
| 2 | + |
| 3 | +def split(filename, delimiter=',', row_limit=10000): |
| 4 | + import csv |
| 5 | + output_name_template='output_%s.csv' |
| 6 | + output_path='.' |
| 7 | + keep_headers=True |
| 8 | + output_name_template = filename + output_name_template |
| 9 | + filehandler = open(filename+".csv",'r') |
| 10 | + reader = csv.reader(filehandler, delimiter=delimiter) |
| 11 | + current_piece = 1 |
| 12 | + current_out_path = os.path.join( |
| 13 | + output_path, |
| 14 | + output_name_template % current_piece |
| 15 | + ) |
| 16 | + current_out_writer = csv.writer(open(current_out_path, 'w'), delimiter=delimiter) |
| 17 | + current_limit = row_limit |
| 18 | + if keep_headers: |
| 19 | + headers = reader.next() |
| 20 | + current_out_writer.writerow(headers) |
| 21 | + for i, row in enumerate(reader): |
| 22 | + if i + 1 > current_limit: |
| 23 | + current_piece += 1 |
| 24 | + current_limit = row_limit * current_piece |
| 25 | + current_out_path = os.path.join( |
| 26 | + output_path, |
| 27 | + output_name_template % current_piece |
| 28 | + ) |
| 29 | + current_out_writer = csv.writer(open(current_out_path, 'w'), delimiter=delimiter) |
| 30 | + if keep_headers: |
| 31 | + current_out_writer.writerow(headers) |
| 32 | + current_out_writer.writerow(row) |
| 33 | + |
| 34 | +def main(): |
| 35 | + file_name = raw_input("Enter name of the csv file(csv file should be present in the pwd):") |
| 36 | + num_of_rows = raw_input("Enter number of rows each split should contain:") |
| 37 | + try: |
| 38 | + split(str(file_name),row_limit = int(num_of_rows)) |
| 39 | + print("Output files successfully saved!") |
| 40 | + |
| 41 | + except Exception as e: |
| 42 | + print("Something went wrong in importing given file...Check below:\n") |
| 43 | + print(e) |
| 44 | + |
| 45 | +if __name__ == "__main__": |
| 46 | + main() |
0 commit comments