Примечание: не тестировалось. Используйте на свой страх и риск.
Основная идея состоит в том, чтобы прочитать данные кусками (количество строк) и добавить их в файл, передав аргумент chunksize
в read_csv
. Этот аргумент может быть необязательно передан в to_csv
для той же цели. Хотя я не профилировал этот код, в целом чтение в чанах и запись в чанках может улучшить производительность ввода-вывода, особенно для больших файлов.
def combine_directory_txt(file_paths, output_filename, chunksize):
"""Merge collection of files.
:param file_paths: Collection of paths of files to merge.
:param output_filename: Path of output file (i.e., merged file).
:param chunksize: Number of lines to read in at one time.
"""
with open(output_filename, "wb") as outfile:
chunk_transfer(file_paths[0], outfile, chunksize, append=False)
for path in file_paths[1:]:
chunk_transfer(path, outfile, chunksize, append=True)
def chunck_transfer(path, outfile, chunksize, append, include_index=False):
"""Transfer file at path to outfile in chunks.
:param path: Path of file to transfer.
:param outfile: File handler for output file.
:param chunksize: Number of lines to read at a time.
:param append: Whether to append to file or write new file.
:param include_index: Whether to include index of dataframe.
"""
with open(path, "rb") as infile:
df = pd.read_csv(infile,
sep='|',
error_bad_lines=False,
# low_memory=False,
encoding='mbcs',
chunksize=chunksize)
if append:
include_header = False
mode = 'a'
else:
include_header = True
mode = 'w'
# Possible to pass chunksize as an argument to to_csv
df.to_csv(outfile, mode=mode, header=include_header, index=include_index)