Python,将元组写入二进制文件

时间:2017-03-20 02:07:15

标签: python tuples binaryfiles

我正在尝试编写元组('hola', 'cheese', '1235265')('hey', 'weird', '30193')从mysql DB获取,将值放入二进制文件

我看到它有DB表作为元组。试图转换成二进制,没有奏效。 所以我用元组尝试了另一个 - > string - >二进制,仍有错误... 有没有什么好的方法可以在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;

1 个答案:

答案 0 :(得分:0)

从编码的角度来看,您可以轻松地将数据的二进制表示写入文件,而不是一个好主意。回读也不容易,但这将有效:

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()