[英]Python, write tuple into binary file
I'm trying to write tuple ('hola', 'cheese', '1235265')
, ('hey', 'weird', '30193')
getting from mysql DB, putting values into binary file 我正在尝试从mysql DB获取元组
('hola', 'cheese', '1235265')
, ('hey', 'weird', '30193')
,并将值放入二进制文件
I saw it got DB table as tuple. 我看到它具有DB表作为元组。 Tried to convert into binary, didn't work well.
试图将其转换为二进制文件,但效果不佳。 So i tried another with tuple -> string -> binary, still has an error... is there any good ways to write tuple to binary file in Python?
所以我尝试了另一个元组->字符串->二进制,仍然有一个错误...是否有什么好方法可以在Python中将元组写入二进制文件?
for i in text_query:
query = "select * from " + i
curs.execute(query)
# Data Fetch from Mysql
rows = curs.fetchall()
results = [".".join(map(str, r)) for r in rows]
make_file(name,i,results)
conn.close()
def make_file(name, filename, rows):
if filename == 'student':
with open(name + '_' + filename + '.dat', 'wb') as fp:
for i in rows:
fp.write(bytearray(rows + '\n'))
elif filename == 'course':
with open(name + '_' + filename + '.dat', 'wb') as fp:
for i in rows:
fp.write(bytearray(rows + '\n'))
elif filename == 'course_taken':
with open(name + '_' + filename + '.dat', 'wb') as fp:
for i in rows:
fp.write(bytearray(rows + '\n'))
else:
return 0;
You can write a binary representation of your data to file easily enough, not that it would be a good idea, from an encoding point of view. 从编码的角度来看,您可以很容易地将数据的二进制表示形式写入文件,但这并不是一个好主意。 Nor will it be easy to read back in, but this will work:
读起来也不容易,但这可以工作:
def make_text_file(name, filename, rows):
if filename == 'student': #
with open(name + '_' + filename + '.txt', 'w') as fp:
row_index = 0
fp.write('<record start>')
for i in rows:
row_index += 1
fp.write('<row {0}>{1}</row>'.format(row_index, i))
fp.write('<record end>\n')
def make_binary_file(name, filename, rows):
if filename == 'student':
with open(name + '_' + filename + '.dat', 'wb') as fp:
row_index = 0
for i in rows:
row_index += 1
fp.write(bytes((i), 'utf8'))
def test_things():
""" Generate some data to write to file """
rows = ('hola', 'cheese', '1235265')
#make_file('student', 'test_student.txt', rows)
make_text_file('test', 'student', rows)
rows = ('hey', 'weird', '30193')
make_binary_file('test', 'student', rows)
if __name__ == '__main__':
test_things()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.