python 将列表写到二进制文件中

Python011

python 将列表写到二进制文件中,第1张

from struct import Struct

def write_records(records, format, f):

'''

Write a sequence of tuples to a binary file of structures.

'''

record_struct = Struct(format)

for r in records:

f.write(record_struct.pack(*r))

if name == ' main ':

records = [ (1, 2.3, 4.5),

(6, 7.8, 9.0),

(12, 13.4, 56.7) ]

with open('data.b', 'wb') as f:

write_records(records, '<idd', f)

from struct import Struct

def read_records(format, f):

record_struct = Struct(format)

chunks = iter(lambda: f.read(record_struct.size), b'')

return (record_struct.unpack(chunk) for chunk in chunks)

if name == ' main ':

with open('data.b','rb') as f:

for rec in read_records('<idd', f):

# Process rec

...

用"*"和\xNN. 例子:

写入1024个二进制值0x00:

file('a.bin','wb').write('\x00'*1024)

在文件尾再添加1024个0x01 :

file('a.bin','ab').write('\x01'*1024)

精确 是什么意思? 指定具体要写入的数字1024还不够精确

如果要保证数据实际写入,刷新IO缓冲区,调用fush或close方法

这有什么难的吗?

你把你的二进制数据可以转成文本串插入,就跟普通的插入一样啊。

import MySQLdb, cPickle

# Connect to a DB, e.g., the test DB on your localhost, and get a cursor

connection = MySQLdb.connect(db="test")

cursor = connection.cursor( )

# Make a new table for experimentation

cursor.execute("CREATE TABLE justatest (name TEXT, ablob BLOB)")

try:

# Prepare some BLOBs to insert in the table

names = 'aramis', 'athos', 'porthos'

data = { }

for name in names:

datum = list(name)

datum.sort( )

data[name] = cPickle.dumps(datum, 2)

# Perform the insertions

sql = "INSERT INTO justatest VALUES(%s, %s)"

for name in names:

cursor.execute(sql, (name, MySQLdb.escape_string(data[name])) )

# Recover the data so you can check back

sql = "SELECT name, ablob FROM justatest ORDER BY name"

cursor.execute(sql)

for name, blob in cursor.fetchall( ):

print name, cPickle.loads(blob), cPickle.loads(data[name])

finally:

# Done. Remove the table and close the connection.

cursor.execute("DROP TABLE justatest")

connection.close( )