Python学习笔记(十一)
一、特殊格式文件
(一)CSV 文件
1、概述
CSV (Comma Separated Values),即逗号分隔值(也称字符分隔值,因为分隔符可以不是逗号),是一种常用的文本
使用时需要导入csv模块
2、常用方法
(1)读取文件
① csv.reader(文件对象)
返回可迭代的reader对象
可以直接通过next()方法进行迭代
import csv
with open("./a.txt", "r", encoding="utf-8-sig") as f:
reader = csv.reader(f)
header = next(reader)
print(header)
for line in reader:
print(line)
② csv.DictReader(文件对象)
文件映射到字典表
import csv
with open("./a.txt", "r", encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
for line in reader:
print(line)
(2)写入文件
① 以元组列表形式写入:csv.writer(文件对象)
writer.writerow(可迭代对象(列表、元组))
import csv
with open("./a.txt", "w", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow((1, 22, 33))
writer.writerows(可迭代嵌套对象)
import csv
with open("./a.txt", "w", encoding="utf-8-sig") as f:
rows = [
(1, 2),
(2, 3),
(3, 4)
]
writer = csv.writer(f)
writer.writerows(rows)
② 以dict形式写入:csv.DictWriter(文件对象,headers)
dictWriter.writeheader():只写入key
import csv
# 结果为 name,age
with open("./a.txt", "w", encoding="utf-8-sig") as f:
d = {
"name":"Tom",
"age":10
}
writer = csv.DictWriter(f, d)
writer.writeheader()
dictWrite.writerows(rows)
import csv
# 结果为 name,age
with open("./a.txt", "w", encoding="utf-8-sig") as f:
d = {
"name":"Tom",
"age":10
}
rows = [
{"name":"v", "age":20},
{"name":"a", "age":30}
]
writer = csv.DictWriter(f, d)
# 写入的数据是:字典组成的列表
writer.writerows(rows)
(二)json 文件
1、概述
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。
使用时需要导入json模块
2、常用方法
(1)json和字符串
① json转字符串
json.dumps(json数据)
import json
jn = {
"name":"Tom",
"age":10,
"xxx":None
}
json_str = json.dumps(jn)
print(json_str)
② 字符串转json
json.loads(字符串)
import json
jn = {
"name":"Tom",
"age":10,
"xxx":None
}
json_str = json.dumps(jn)
print(json_str)
print(json.loads(json_str))
(2)json和文件
① 写json文件
json.dump(data, f)
import json
jn = {
"name":"Tom",
"age":10,
"xxx":None
}
with open("./a.txt", "w", encoding="utf-8") as f:
json.dump(jn, f)
② 读json文件
json.load(f)
import json
jn = {
"name":"Tom",
"age":10,
"xxx":None
}
with open("./a.txt", "r", encoding="utf-8") as f:
print(json.load(f))
三、Excel 文件
使用时需要导入xlrd模块
(一)常用方法
Excel读取
函数名 | 作用 |
---|---|
book = xlrd.open_workbook(“文件名”) | 获取Excel文件对象 |
book.sheets() | 获取所有工作表 |
sheet = book.sheet_by_name(“sheet名称”) | 根据名称获取指定sheet表 |
sheet.name | 获取表名 |
sheet.nrows | 获取表行数 |
sheet.row_values(index) | 获取索引指定的数据行 |