Purpose of this chapter

Learn how to define an object, how to use mysql, how to manipulate CSV, XLSX, PDF files, etc. If the first two stanzas

Learn how to define an object

Code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

# 1. Define the Person class
class Person:

    def __init__(self, name, age) :
        self.name = name
        self.age = age

    def watch_tv(self) :
        print(f'{self.name}Watching TV ')


# 2. Define the loop function
Print odd numbers in 1-max
def test_person() :
    person = Person('Jake'.20)
    print(F 'Prints the address of person:', person)
    print(f'person.name:{person.name}')
    print(f'person.age:{person.age}')
    person.watch_tv()

    person = Person('Koko'.18)
    print(F 'Prints the address of person:', person)
    print(f'person.name:{person.name}')
    print(f'person.age:{person.age}')
    person.watch_tv()


# 3. Implement the Calculate method
# count current value less than 1, current value: 0
# count 1 >= 1: True
# count 2 >= 1: True
# count 10 >= 1: True
test_person()
Copy the code

Execution Result:

How to connect to MySQL

Block of code:

#! /usr/bin/python
# -*- coding: UTF-8 -*-

# pip3 install pymysql

import pymysql

from getpass import getpass

# from mysql.connector import connect, Error
#
host = 'xxxxxxx'
port = 3306
username = 'db_account_member'
password = 'db_account_password'
database = 'some_database'


def connect_db() :
    return pymysql.connect(host=host,
                           port=port,
                           user=username,
                           password=password,
                           database=database,
                           charset='utf8')


def print_error(e) :
    print(F 'error type:{type(e)}')
    print(F 'error contents:{e}')


def close_gracefully(cursor, conn) :
    if cursor:
        cursor.close()
    if conn:
        conn.close()


# query database, can write any query statement
def query(sql) :
    try:
        conn = connect_db()  Create a connection
        cursor = conn.cursor()  Create a cursor
        cursor.execute(sql)  Execute SQL statement
        return cursor.fetchall()
    except pymysql.Error as e:
        print_error(e)
    finally:
        close_gracefully(cursor, conn)



query_sql = 'select * from category where id = 1'
rows = query(query_sql)
print(The data in the category table is as follows:)
print(rows)

Copy the code

Execution Result:

Database related table structure can find me

3. Learn how to read and write CSV

Code:

# -*- coding: utF-8 -*- # 1. Import CSV file_name = '.. /resources/test.csv' # 2. Headers and rows = ['index', 'name', 'sex', 'height', 'year'] rows = [[1, 'Jake', 'male', 177, 20], [2, 'Koko', 'female', 165, 18], [3, 'Mother', 'female', 163, 45], [4, 'Father', 'male', 172, 48]] # 3. Def write_csv(): print(f' file [{file_name}] ready to write ') with open(f'{file_name}', 'w')as f: F_csv = csv.writer(f) f_csv.writerow(headers) f_csv.writerows(rows) print(f' file [{file_name}] has been written ' Read_csv (): print(f' file [{file_name}] ready to read ') with open(f'{file_name}')as f: f_csv = csv.reader(f) for row in f_csv: Print (row) print(f' file [{file_name}] finished ') Perform write_csv write_csv function () print (' -- -- -- -- -- - ') read_csv ()Copy the code

Execution Result:

4. Read XLSX

Code:

# -*- coding: UTF-8 -*- # guide # install dependencies # pip3 install XLRD Sku_file = XLRD. Open_workbook (file_name) print("{0} ") sku_file = XLRD Format (file_name, sku_file.nsheets) print(" {0}".format(sku_file.sheet_names())) print(" {0}".format(sku_file.sheet_names())) Sheet1 is a Sheet1 sheet with 59 rows, 3 columns and # A6 grid values. 1908165140370878 CURRENT_sheet_index = 0 # subscript 0 for the first page TAB current_sheet = sku_file. Sheet_by_index (current_sheet_index) Format (current_sheet.name, current_sheet.nrows, current_sheet.ncols) : print(" TAB page id: {0}, TAB page id: {1}, {2} ") : {0}".format(current_sheet.cell_value(rowx=5, colx=0))) # 3. Print each page of data, [text:'1908154975415329', text:' fabric soles polyurethane soles ', [text:'1908040228021948', text:' fly-woven sole ', text:' sole height is about 3cm '] #... For rx in range(current_sheet.nrows): print(current_sheet.row(rx))Copy the code

Execution Result:

5. Read and write PDF

Code:

import platform
import pdfkit

Wkhtmltopdf = wkhtmltopdf = wkhtmltopdf = wkhtmltopdf
win_path = 'D:/tools/wkhtmltopdf'
non_win_path = '/usr/local/bin/wkhtmltopdf'


def wkhtmltopdf_path() :
    system = platform.system()
    if system == 'Darwin':
        print('Apple system can generate PDF')
        path = non_win_path
    elif system == 'Windows':
        print('For Windows, you can generate PDF')
        path = win_path
    elif system == 'Linux':
        print('Linux system can generate PDF ')
        path = non_win_path
    else:
        print('Other systems do not support PDF generation')
        raise Exception('Other systems do not support PDF generation')
    return path


def pre_config() :
    return pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path())


Generate PDF from link address
def generate_pdf_from_url(url, output_file_path) :
    config = pre_config()
    pdfkit.from_url(url, output_file_path)


Generate PDF from string
def generate_pdf_from_string(str, output_file_path) :
    config = pre_config()
    pdfkit.from_string(str, output_file_path)


generate_pdf_from_url('https://baidu.com'.'.. /temp/baidu_test.pdf')

generate_pdf_from_string('hello'.'.. /temp/hello.pdf')
Copy the code

Wkhtmltopdf this thing must be installed, otherwise it can not generate PDF, will report IO errors, small white do as you can, do not need to understand

The execution result

The resulting file looks like this

baidu_test.pdf

hello.pdf