I have a file that in C++ I load into array using below code:
int SomeTable[10000];
int Loa开发者_开发技巧dTable()
{
memset(SomeTable, 0, sizeof(SomeTable));
FILE * fin = fopen("SomeFile.dar", "rb");
size_t bytesread = fread(SomeTable, sizeof(SomeTable), 1, fin);
fclose(fin);
}
The file is binary code of 10000 integers, so in C++ it could be directly loaded into memory. Is there a fansy way of doing that in Python?
best regards, Rok
Let's write an array into a file using a short C code:
int main ()
{
FILE * pFile;
int a[3] = {1,2,3};
pFile = fopen ( "file.bin" , "wb" );
fwrite (a , 1 , sizeof(a) , pFile );
fclose (pFile);
return 0;
}
The binary file can be loaded directly into a python array
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import array
>>> a=array.array('l') # 'l' is the type code for signed integer
>>> file=open('file.bin','rb')
>>> a.read(file,3)
>>> print a
array('l', [1, 2, 3])
>>> print a[0]
1
精彩评论