Estoy desarrollando un script para dividir un fichero csv en tantos como se soliciten. Pero tengo un problema cuando la división de las lineas del fichero csv no es exacta con el número de ficheros que se quieren generar. ¿Cómo puedo recoger esas líneas sobrantes e incluirlas en el último fichero csv que genero?
He llegado a esto pero no hay manera...
def pass_file_to_list(filename, filediv):
data_list = list()
with open(filename, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in spamreader:
bf_name = row
data_list.append(bf_name)
return divide_list(data_list, filediv)
def divide_list(data_list, filediv):
lines_to_file = int(len(data_list) / filediv)
lines_rest = int(len(data_list) % filediv)
small_file_divided = list()
for i in range(filediv):
names = []
for num in range(i * lines_to_file, (i + 1) * lines_to_file):
names.append(data_list[num])
small_file_divided.append(names)
return small_file_divided
def write_csv_files(data_list, count):
with open(name=path + '/subfile_' + str(count) + '.csv', mode='wb') as
csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
for data in data_list:
spamwriter.writerow(data)
if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding('utf-8')
parser = OptionParser(usage="%prog --filename --pos ")
parser.add_option("-f", "--filename", action="store", type="string",
dest="filename", help="[REQUIRED] File name with the data to be searched")
parser.add_option("-d", "--div", action="store", type="string", dest="div",
help="[REQUIRED] Number of files you want")
(options, args) = parser.parse_args()
if not options.filename:
sys.exit(-1)
else:
filename = options.filename
path = "/".join(filename.split('/')[:-1])
if not options.div:
sys.exit(-1)
else:
filediv = int(options.div)
file_list = pass_file_to_list(filename, filediv)
count = 0
for x in file_list:
count += 1
write_csv_files(x, count)