python中的.dat文件 [英] .dat file in python
问题描述
我正在使用OpenCV在python中做一个项目.我必须将大量的整数数据(数据库中图像的特征)存储在单独的文件中.我可以使用.txt文件,但它将整数值存储为字符串. 有什么方法可以将整数值直接存储为python中的整数,例如MATLAB中的.dat文件??
I'am doing a project in python using OpenCV. I have to store a large amount of integer data(features of images in the database) in a separate file. I can use .txt file but it stores integer values as strings. Is there any way that I can store integer values directly as integers in python like .dat file in MATLAB.?
推荐答案
您可以使用结构将整数打包为字节格式并将其写入dat文件.
You can use struct to pack the integers in a bytes format and write them to a dat file.
对于整数,这将导致每个整数包含4个字节的文件,如果您的数字很大,则可以节省一些空间(文本格式).如果数字较小,则csv格式可能会更好.
With integers, this will result in a file that contains 4 bytes per integer, which would save a bit of space (over text format) if you have very large numbers. If you have smaller numbers, a csv format may be better.
import struct
data = [1,2,3,4,5,6,7,8,9]
with open('data.dat', 'wb') as data_file:
data_file.write(struct.pack('i'*len(data), *data))
然后将其读回
with open('data.dat', 'rb') as data_file:
values = struct.unpack('i'*len(data), data_file.read())
这篇关于python中的.dat文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!