Search code examples
pythontuplesbinaryfiles

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

I saw it got DB table as tuple. 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?

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;

Solution

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