[python] data table to csv

1 Basic structure

1.1 Data

insert image description here

1.2 Data structure

insert image description here

2 codes

  • code:
import mysql.connector
import csv

def getPerson():
    # 数据库初始化
    cnx = mysql.connector.connect(user='root', password='root', database='test')
    cursor = cnx.cursor()
    query = 'SELECT * FROM person'
    cursor.execute(query)
    data = cursor.fetchall()

    # 写入csv
    with open('person.csv', 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['id', 'name', 'age', 'sex'])
        for row in data:
            lst = list(row)
            i = 0
            for index in lst:
                # 字节转换
                if isinstance(index,bytearray):
                    new = index.decode('utf-8')
                    lst[i] = new
                i += 1
            tup = tuple(lst)
            writer.writerow(tup)

    # 关闭连接
    cursor.close()
    cnx.close()

if __name__ == '__main__':
    getPerson()
  • output:
    insert image description here

3 tip

Go converts data table to csv: https://blog.csdn.net/qq_45859826/article/details/131451336

Guess you like

Origin blog.csdn.net/qq_45859826/article/details/131452176