3.1-python爬虫之文件存储

系列文章目录

python爬虫目录


文章目录

  • 系列文章目录
  • 前言
  • 一、json文件处理
    • 1、什么是json
    • 2、JSON支持数据格式
    • 3、字典和列表转JSON
      • python对象转json字符串:dumps
      • python对象转json文件:dump
      • json字符串转成Python对象:loads
      • json文件转成Python对象:load
  • 二、csv文件处理
    • 1、什么是csv
    • 2、CSV读写操作
      • python数据写到csv文件
      • 读取csv文件
  • 三、excel文件处理


前言

摘录自B站对应课程笔记
不愧是清华大佬!把Python网络爬虫讲得如此简单明了!从入门到精通保姆级教程(建议收藏)

以下是本篇文章正文内容,下面案例可供参考


一、json文件处理

1、什么是json

JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。

在线格式化网站:https://www.json.cn/

2、JSON支持数据格式

  1. 对象(字典)。使用花括号。
  2. 数组(列表)。使用方括号。
  3. 整形、浮点型、布尔类型还有null类型。
  4. 字符串类型(字符串必须要用双引号,不能用单引号)。

多个数据之间使用逗号分开。json本质上就是一个字符串。

3、字典和列表转JSON

python对象转json字符串:dumps

import json
 
# 将 python 对象转换成 json 字符串
persons = [
    {
        "name": "xu1",
        "age": 11,
        "height": 171
    },
    {
        "name": "xu2",
        "age": 12,
        "height": 172
    },
]
persons_str = json.dumps(persons)
print(type(persons_str))  # 
print(persons_str)  # [{"name": "xu1", "age": 11, "height": 171}, {"name": "xu2", "age": 12, "height": 172}]

因为 json 在 dumps 的时候,只能存放 ascii 的字符,因此会将中文进行转义,这时候我们可以使用
ensure_ascii=False 关闭这个特性。
在Python中。只有基本数据类型才能转换成JSON格式的字符串。也即:int、float、str、list、dict、tuple。

# json 无法序列化自定义对象
class Person(object):
    country="china"
a = {
    "person": Person()
}
json.dumps(a)
"""
报错:
    TypeError: Object of type Person is not JSON serializable
"""

python对象转json文件:dump

import json
 
persons = [
    {
        "name": "xu1_许三多",
        "age": 11,
        "height": 171
    },
    {
        "name": "xu2_许三多",
        "age": 12,
        "height": 172
    },
]
# 方法一:将字符串写入文件
# persons_str = json.dumps(persons)
# with open("persons.json", "w", encoding="utf-8") as fp:
#     fp.write(persons_str)
 
# 方法二:直接通过 json.dump 写入对象
with open("persons.json", "w", encoding="utf-8") as fp:
    json.dump(persons, fp, ensure_ascii=False)

json字符串转成Python对象:loads

import json
 
persons_str = '[{"name": "xu1", "age": 11, "height": 171}, {"name": "xu2", "age": 12, "height": 172}]'
persons = json.loads(persons_str)
print(type(persons))
for p in persons:
    print(p)
"""
结果:
    
    {'name': 'xu1', 'age': 11, 'height': 171}
    {'name': 'xu2', 'age': 12, 'height': 172}
"""

json文件转成Python对象:load

with open("persons.json", "r", encoding="utf-8") as fp:
    persons = json.load(fp)
    print(type(persons))
    for p in persons:
        print(p)
"""
结果:
    
    {'name': 'xu1_许三多', 'age': 11, 'height': 171}
    {'name': 'xu2_许三多', 'age': 12, 'height': 172}
"""

二、csv文件处理

1、什么是csv

SV文件是最常用的一个文件存储方式。逗号分隔值(Common-Separated Values,CSV)文件以纯文本形式存储表格数据(注:分隔字符也可以是其他字符)。纯文本说明该文件是一个字符序列,不包含必须像二进制数字那样被解读的数据。

CSV文件由任意数目记录组成,记录间以某种换行符分隔;每条记录由若干字段组成,字段间以字符(如逗号)或字符串分隔。

2、CSV读写操作

python数据写到csv文件

按行写入

"""
写入数据到csv文件,需要创建一个writer对象,主要用到两个方法。一个是writerow,这个是写入一行。一个是writerows,这个是写入多行。示例代码如下:
"""
import csv
 
headers = ["name", "age", "height"]
datas = [
    ("许1", 89, 150),
    ("许2", 64, 160),
    ("许3", 60, 170),
]
with open("persons.csv", "w", encoding="utf-8", newline="") as  fp:
    writer = csv.writer(fp)  # 创建一个可写对象
    writer.writerow(headers)  # 写入一行数据
    writer.writerows(datas)  # 写入多行数据

按字典对象写入

import csv
 
headers = ["name", "age", "height"]
datas = [
    {"name":"许1", "age": 12, "height": 23},
    {"name": "许2", "age": 22, "height": 123},
    {"name": "许3", "age": 32, "height": 223},
]
with open("persons2.csv", "w", encoding="utf-8", newline="") as fp:
    writer = csv.DictWriter(fp, headers)  # 创建一个可写对象
    # 注意:写如表头的时候,需要调用 writeheader 方法
    writer.writeheader()
    writer.writerow({"name":"许1", "age": 12, "height": 23})  # 写入一行数据
    writer.writerows(datas)  # 写入多行数据

读取csv文件

按下标获取数据

import csv
with open("persons.csv", "r", encoding="utf8") as fp:
    reader = csv.reader(fp)
    print("返回的类型:{}".format(type(reader)))
    print("第一行内容:{}".format(next(reader)))
    for p in reader:
        print("name = {}, age = {}, height = {}".format(p[0], p[1], p[2]))
"""
结果:
    返回的类型:
    第一行内容:['name', 'age', 'height']
    name = 许1, age = 89, height = 150
    name = 许2, age = 64, height = 160
    name = 许3, age = 60, height = 170
"""

通过标题来获取数据

import csv
with open("persons2.csv", "r", encoding="utf8") as fp:
    # 使用 DictReader 创建 reader 对象,不会包含标题那行的数据
    # reader 是一个迭代器, 遍历时返回字典对象
    reader = csv.DictReader(fp)
    print(type(reader))
    for p in reader:
        print("name = {}, age = {}, height = {}".format(p["name"], p["age"], p["height"]))
"""
结果:
    
    name = 许1, age = 12, height = 23
    name = 许1, age = 12, height = 23
    name = 许2, age = 22, height = 123
    name = 许3, age = 32, height = 223
"""

三、excel文件处理

3.1-python爬虫之文件存储_第1张图片
excel操作较多,方式较多,可参考以下文章(全文3万+字,需要什么功能直接使用搜索就行):
全网最全Python操作Excel教程,建议收藏!

你可能感兴趣的:(python爬虫学习笔记,字符串,列表,python,csv,json)