I have made CSV file slicer. This is my first and biggest piece of code on Python. It takes one .csv
file from current folder and then slices it to n parts and adds a first column, if provided.
import csv
import math
import os
import re
import sys
# Reading and returning files in current directory
def read_files():
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
return [f for f in os.listdir(__location__) if os.path.isfile(f)]
# Removing files which match certain pattern
def remove_old_files():
for f in read_files():
if re.search("^[0-9]+\.csv$", str(f)) is not None:
os.remove(f)
# Getting file to split in current directory
def get_file_to_split():
for f in read_files():
if re.search(".*\.csv$", str(f)) is not None:
split(f, int(sys.argv[1]))
# Split file into n pieces
def split(csv_file, pieces):
first_col = None
if len(sys.argv) > 2:
first_col = sys.argv[2]
with open(csv_file, 'r') as c:
reader = csv.reader(c)
data = list(reader)
cols_to_write = math.ceil(data.__len__() / pieces)
chunks = [data[x:x + cols_to_write] for x in range(0, len(data), cols_to_write)]
for num_file in range(pieces):
filename = str(num_file) + ".csv"
with open(filename, 'w') as f:
w = csv.writer(f)
for i in range(cols_to_write):
try:
if first_col is not None and i == 0:
w.writerow([first_col])
w.writerow(chunks[num_file][i])
except IndexError:
pass
print("Done")
if __name__ == "__main__":
if int(sys.argv[1]) <= 0:
raise SystemExit("Piece count must be natural number greater than zero.")
remove_old_files()
get_file_to_split()