python - 内存效率 .txt 附加 Python
问题描述
我在 Python 中创建了一个 .txt 文件目录列表,然后编写了一个函数来组合这些文件。
def combine_directory_txt(FilePaths):
"""
This function will combine all files in a directory by importing each,
and appending them to a single output. It only works for csv's (.txt) with
a delimeter of "|"
"""
Output = pd.DataFrame() # Dataframe which will store the final table
Increment = 0
Total = len(FilePaths)
# Import each file and join them together
for file in FilePaths:
Increment += 1
Import = pd.read_csv(file, sep = '|', error_bad_lines = False,
low_memory = False, encoding='mbcs' )
Output = Output.append(Import)
print (Increment, " of ", Total, " joined")
del Import
return Output
这工作正常,除了我的电脑正在与 MemoryErrors 作斗争。有没有更有效的方法来做到这一点?我意识到我已经使用了“low_memory = false”,这个过程将每月重复一次,所以我不知道列会是什么样子,而且由于所有 dtype 警告,我的代码很早就失败了。这是正确的方法吗?我是否应该编写代码来确定 dtypes 是什么,然后分配它们以减少内存?
解决方案
您的方法是将每个 CSV 文件读入内存并将它们全部组合并返回结果数据帧。相反,您应该一次处理一个 CSV 文件,每次将结果写入output.csv
文件。
下面的脚本显示了如何做到这一点。它添加用于输出的文件名。它假定运行中的所有文件共享相同的格式,并且每个文件都具有相同的标题。标头被写入输出 CSV 文件一次,然后在读取时跳过。
import csv
def combine_directory_txt(file_paths, output_filename):
# Get the header from the first CSV file passed
with open(file_paths[0], "rb") as f_input:
header = next(csv.reader(f_input, delimiter="|"))
with open(output_filename, "wb") as f_output:
csv_output = csv.writer(f_output, delimiter="|")
csv_output.writerow(header) # Write the header once
for file_name in file_paths:
with open(file_name, "rb") as f_input:
csv_input = csv.reader(f_input, delimiter="|")
next(csv_input) # Skip header
csv_output.writerows(csv_input)
combine_directory_txt(["mbcs_1.txt", "mbcs_2.txt"], "output.csv")
使用这种方法,内存需求将大大降低。
推荐阅读
- javascript - Uncaught SyntaxError: Unexpected token '<' for doctype 当我向 Vue 添加外部 js 文件时
- spring - Log4j 日志文件未在指定位置 springboot 创建
- excel - 带有 TODAY() 和其他日期的 AVERAGEIF/AVERAGEIFS
- java - 如何弹出、查看和获取尺寸?
- wordpress - ACF 渲染块使 wp 中的编辑页面不读取任何 CSS
- yellowbrick - 如何更改黄砖地块中的标记?
- artificial-intelligence - 如何使用 4x4 tic tac toe 的 minimax 算法使 AI 更有效?
- tomcat - 为什么有些 HTTP/HTTPS 随机以 1|X 开头?
- vue.js - Toggle Boolean like toggling classlist Vue 2
- c++ - 如何在犰狳中序列化稀疏矩阵并与提升的 mpi 实现一起使用?