我有兩個 30 GB 的 CSV 檔案,每個檔案包含數千萬條記錄。

他們使用逗號作為分隔符,并保存為 UTF-16(感謝 Tableau :-( )
我希望使用逗號而不是制表符將這些檔案轉換為 utf-8-sig。
我嘗試了以下代碼(之前宣告了一些變數):
csv_df = pd.read_csv(p, encoding=encoding, dtype=str, low_memory=False, error_bad_lines=True, sep=' ')
csv_df.to_csv(os.path.join(output_dir, os.path.basename(p)), encoding='utf-8-sig', index=False)
我也試過: Convert utf-16 to utf-8 using python
兩者都作業緩慢,幾乎永遠不會完成。
有沒有更好的方法來進行轉換?也許 Python 不是最好的工具?
理想情況下,我希望將資料存盤在資料庫中,但恐怕目前這不是一個合理的選擇。
謝謝!
uj5u.com熱心網友回復:
我在兩分鐘內轉換了一個 35GB 的檔案,請注意,您可以通過更改頂行中的常量來優化性能。
BUFFER_SIZE_READ = 1000000 # depends on available memory in bytes
MAX_LINE_WRITE = 1000 # number of lines to write at once
source_file_name = 'source_fle_name'
dest_file_name = 'destination_file_name'
source_encoding = 'file_source_encoding' # 'utf_16'
destination_encoding = 'file_destination_encoding' # 'utf_8'
BOM = True # True for utf_8_sig
lines_count = 0
def read_huge_file(file_name, encoding='utf_8', buffer_size=1000):
def read_buffer(file_obj, size=1000):
while True:
data = file_obj.read(size)
if data:
yield data
else:
break
source_file = open(file_name, encoding=encoding)
buffer_in = ''
for buffer in read_buffer(source_file, size=buffer_size):
buffer_in = buffer
lines = buffer_in.splitlines()
buffer_in = lines.pop()
if len(lines):
yield lines
else:
break
def process_data(data):
def write_lines(lines_to_write):
with open(dest_file_name, 'a', encoding=destination_encoding) as dest_file:
if BOM and dest_file.tell() == 0:
dest_file.write(u'\ufeff')
dest_file.write(lines_to_write)
return ''
global lines_count
lines = ''
for line in data:
lines_count = 1
lines = (line '\n')
if not lines_count % MAX_LINE_WRITE:
lines = write_lines(lines)
if len(lines):
with open(dest_file_name, 'a', encoding=destination_encoding) as dest_file:
write_lines(lines)
for buffer_data in read_huge_file(source_file_name, encoding=source_encoding, buffer_size=BUFFER_SIZE_READ):
process_data(buffer_data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/479713.html
