JSON文件

JSON(JavaScript Object Notation,JS对象标记)是一种轻量级的数据交换格式。
JSON支持的数据格式:对象(字典)、数组(列表)、字符串类型(字符串必须使用双引号,不能使用单引号)、整形、浮点型、布尔型、null型。多个数据之间使用逗号分隔,json本质上就是一个字符串。

Python对象转json字符串

  1. import json
  2. books = [
  3. {
  4. 'name': "水浒传",
  5. 'prices': 56
  6. },
  7. {
  8. 'name': "三国演义",
  9. 'prices': 79
  10. }
  11. ]
  12. # dumps将Python对象转化为json字符串
  13. result = json.dumps(books, ensure_ascii=False)
  14. print(result)
  15. # dump直接将Python对象转化为json字符串写入文件中
  16. with open('books.json', 'w', encoding='utf-8') as f:
  17. json.dump(books, f, ensure_ascii=False)

如上所示,使用dumps()和dump()方法都可以完成转换,其中ensure_ascii参数默认为True,默认转换后只能存储ascii格式的,不能存储中文,我们可以将其设置为False。

json字符串转Python对象

  1. import json
  2. json_str = '[{"name": "水浒传", "prices": 56}, {"name": "三国演义", "prices": 79}]'
  3. # loads将json字符串转化为Python对象
  4. result = json.loads(json_str)
  5. print(result, type(result))
  6. # load将文件中的json字符串转化为Python对象
  7. with open('books.json', 'r', encoding='utf-8') as f:
  8. res = json.load(f)
  9. print(res, type(res))

CSV文件

CSV文件的读取

  1. import csv
  2. # 按行读取csv文件,每一行返回一个列表
  3. with open('快代理-ip.csv', 'r', encoding='utf-8') as f:
  4. result = csv.reader(f)
  5. for i in result:
  6. print(i)
  7. # 按字典的形式读取,这种方法有索引,可以通过索引获取值
  8. with open('快代理-ip.csv', 'r', encoding='utf-8') as f:
  9. res = csv.DictReader(f)
  10. for i in res:
  11. print(i['IP'])

CSV文件的写入

  1. import csv
  2. headers = ['name', 'age']
  3. stu_list = [
  4. ['wanger', 10],
  5. ['lisi', 15],
  6. ['lixiang', 20]
  7. ]
  8. stu_dict = [
  9. {'name': 'wanger', 'age': 10},
  10. {'name': 'lisi', 'age': 15},
  11. {'name': 'lixiang', 'age': 20},
  12. ]
  13. # writer就是一行一行的写入,指定newline=''去掉多余的换行
  14. with open('students.csv', 'w', encoding='utf-8', newline='') as f:
  15. writer = csv.writer(f)
  16. writer.writerow(headers) # 先写入表头数据
  17. writer.writerows(stu_list) # 学生信息多行写入
  18. # DictWriter按字典形式写入
  19. with open('students.csv', 'w', encoding='utf-8', newline='') as f:
  20. # 除了传入要写入的文件,还有表头信息
  21. writer = csv.DictWriter(f, headers)
  22. # 但以上表头数据仍未写入,需要调用以下方法才能正式写入表头数据
  23. writer.writeheader()
  24. writer.writerows(stu_dict)

Excel文件

安装相关库

  1. pip install xlrd # 读
  2. pip install xlwt # 写

sheet相关操作

  1. import xlrd
  2. workbook = xlrd.open_workbook("学生表.xls")
  3. # 获取所有sheet名字
  4. print(workbook.sheet_names())
  5. # 根据索引获取指定的sheet对象
  6. sheet1 = workbook.sheet_by_index(0)
  7. print(sheet1.name)
  8. # 根据名字获取指定的sheel对象
  9. sheet2 = workbook.sheet_by_name('1班')
  10. print(sheet2.name)
  11. # 获取所有的sheet对象
  12. sheet_list = workbook.sheets()
  13. for i in sheet_list:
  14. print(i.name)
  15. # 获取指定sheet的行数和列数
  16. sheet3 = workbook.sheet_by_index(0)
  17. print("行数:{} 列数:{}".format(sheet3.nrows, sheet3.ncols))

Cell相关操作

这里演示的文件数据如下图:
学生表数据.png

  1. import xlrd
  2. workbook = xlrd.open_workbook("学生表.xls")
  3. sheet = workbook.sheet_by_index(0)
  4. # 获取指定行和列的cell对象
  5. cell1 = sheet.cell(0, 0)
  6. print(cell1.value) # 输出:姓名
  7. # 获取指定行的某几列对象
  8. cell2_list = sheet.row_slice(1, 0, 3)
  9. for i in cell2_list:
  10. print(i.value) # 输出:王二 10.0
  11. # 获取指定列的某几行对象
  12. cell3_list = sheet.col_slice(0, 0, 6)
  13. for i in cell3_list:
  14. print(i.value) # 输出:姓名 王二 李四 张三 刘五 王二
  15. # 获取指定行列的值
  16. cell4 = sheet.cell_value(1, 0)
  17. print(cell4) # 输出:王二
  18. # 获取指定行某几列的值
  19. cell5 = sheet.row_values(0, 0, 3)
  20. for i in cell5:
  21. print(i) # 输出:姓名 年龄
  22. # 获取指定列某几行的值
  23. cell6 = sheet.col_values(0, 0, 6)
  24. for i in cell6:
  25. print(i) # 输出:姓名 王二 李四 张三 刘五 王二

Cell的数据类型

类型 描述
xlrd.XL_CELL_EMPTY 空白数据类型 0
xlrd.XL_CELL_TEXT 文本类型 1
xlrd.XL_CELL_NUMBER 数值类型 2
xlrd.XL_CELL_DATE 日期时间类型 3
xlrd.XL_CELL_BOOLEAN 布尔类型 4

当获取到具体的某个cell后,可以通过cell.ctype来获得这个单元格的类型

写入Excel文件

  1. import xlwt
  2. workbook = xlwt.Workbook()
  3. sheet = workbook.add_sheet('sheet1')
  4. # 写入表头数据
  5. headers = ['姓名', '年龄']
  6. for index, header in enumerate(headers):
  7. sheet.write(0, index, header)
  8. # 写入第一列
  9. names = ['张三', '王五']
  10. for index, name in enumerate(names):
  11. sheet.write(index+1, 0, name)
  12. # 写入年龄
  13. sheet.write(1, 1, 10)
  14. sheet.write(2, 1, 15)
  15. # 保存
  16. workbook.save("excel-write.xls")
  1. **如果想要在原来workbook对象上添加新的cell,那么需要调用put_cell来添加。如:sheet.put_cell(row, col, Cell的数据类型, data, None)**<br /> 由于原有文件的读取使用xlrd模块,这个模块只能读,无法写入数据,因此调用put_cell()后,我们想保存的数据其实在内存上,没有保存到外存的文件中。如果想将新表的数据保存成文件,那就用xlwt模块新建一个表,将内存中的数据拷贝到新表中进行保存。

MySQL数据库

安装MySQL数据库

  1. # 安装
  2. yay -S mysql
  3. # 初始化mysql,记住输出的root密码
  4. sudo mysqld --initialize --user=mysql --basedir=/usr --datadir=/var/lib/mysql
  5. # 启动mysql服务
  6. sudo systemctl start mysqld.service
  7. # 查看mysql状态
  8. systemctl status mysqld.service
  9. # 登录mysql服务,输入默认密码即可
  10. mysql -u root -p
  11. # 修改默认密码
  12. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'yourpassword';

Python连接到MySQL数据库

首先需要安装一个模块

  1. pip install pymysql

简单的连接例子如下:

  1. import pymysql
  2. # 使用pymysql.connect方法连接数据库
  3. db = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='crawler')
  4. # 如果要操作具体的数据库,还需要获取db上的cursor对象
  5. cursor = db.cursor()
  6. # 使用cursor来执行sql语句,查询temp表中的所有内容
  7. cursor.execute('select * from temp')
  8. # 返回查询结果的第一行
  9. result = cursor.fetchone()
  10. print(result)

插入操作

  1. import pymysql
  2. db = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='crawler')
  3. cursor = db.cursor()
  4. # 插入一条数据的sql语句
  5. sql = "insert into temp(id,title,context) VALUES (null,'one','第一次插入')"
  6. # 执行sql语句
  7. cursor.execute(sql)
  8. # 提交我们的操作,数据库中的数据会因为我们的操作而发生改变,就需要进行提交
  9. db.commit()
  10. # 关闭数据库
  11. db.close()
  12. # -----------------------------------------------------
  13. # -------如果我们的插入的数据需要不断变化,不论什么类型,都用%s进行占位,如下:
  14. sql = "insert into temp(id,title,context) VALUES (null,%s,%s)"
  15. cursor.execute(sql, ('变量插入', '什么数据都用%s来代替'))
  16. # ------------------------------------------------------

查询操作

  1. import pymysql
  2. db = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='crawler')
  3. cursor = db.cursor()
  4. # 查询语句
  5. sql = "select id, title from temp where id>3"
  6. cursor.execute(sql)
  7. # 每次获取一条数据
  8. result1 = cursor.fetchone()
  9. result2 = cursor.fetchone()
  10. print(result1, result2)
  11. # 接收全部的返回结果
  12. result = cursor.fetchall()
  13. print(result)
  14. # 可以获取指定条数的数据,如果指定的大小超过结果的数量,也会返回所有的结果
  15. result = cursor.fetchmany(3)
  16. print(result)
  17. # 关闭数据库
  18. db.close()

删除操作

  1. import pymysql
  2. db = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='crawler')
  3. cursor = db.cursor()
  4. # 删除语句
  5. sql = "delete from temp where title='xxx'"
  6. cursor.execute(sql)
  7. db.commit()
  8. # 关闭数据库
  9. db.close()

更新操作

  1. import pymysql
  2. # 如果存在编码问题,可以在连接时通过charset来指定编码方式
  3. db = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='crawler', charset='utf8')
  4. cursor = db.cursor()
  5. # 更新语句
  6. sql = "update temp set title='更新后的title' where id=1"
  7. cursor.execute(sql)
  8. db.commit()
  9. # 关闭数据库
  10. db.close()