一、文件基本操作
1.文件操作 - 文件内容的操作,主要是文件读操作和写操作
2.文件操作基本步骤
第一步:打开文件
第二步:读文件-获取文件内容/写文件-将内容写入文件中
第三步:关闭文件
1)打开文件
open(file,mode=‘r’,…,encoding=None) - 以指定的方式打开指定文件并且返回一个文件对象
a.file - 字符串,需要打开的文件的路径
b.mode - 文件打开方式(决定打开文件后能够支持的操作是读还是写;决定打开文件后操作数据的数据类型是文本数据还是二进制数据)
控制读写的mode值
‘r’ - (默认)只读, 被打开的文件不存在会报错
‘w’ - 只写,打开的时候会先删除原文件内容, 被打开的文件不存在会自动创建
‘a’ - 只写, 打开的时候不会删除原文件内容, 被打开的文件不存在会自动创建
‘x’ - 只写, 新建文件(打开已经存在的文件会报错,打开不存在的文件会自动创建)
控制数据类型的mode值
‘t’ - 文件的数据是文本数据(字符串类型, 默认值,只有文本文件操作的时候才能使用)
‘b’ - 文件的数据是二进制数据(bytes类型,适用于任何文件,不能设置encoding的值)
注意: mode值的两种控制方式要一起用, ‘rt’/‘tr’/‘rb’/‘br’, ‘wt’/‘tw’/‘wb’/‘bw’, …
c.encoding - 文本文件的编码方式,一般设置为’utf-8’
- 读写文件
文件对象.read()
文件对象.write(内容)
文件路径
open('files/poem.txt')
# open('files/poem1.txt')
读写方式
# 'r'
f = open('files/poem.txt', 'r')
f.read()
# f.write('abc') # io.UnsupportedOperation: not writable
# f = open('files/poem1.txt', 'r') # FileNotFoundError: [Errno 2] No such file or directory: 'files/poem1.txt'
# 'w'
f = open('files/poem.txt', 'w')
f.write('abc')
# f.read() # io.UnsupportedOperation: not readable
f = open('files/poem1.txt', 'w')
# 'a'
f = open('files/诗.txt', 'a')
f.write('abc')
# f.read() # io.UnsupportedOperation: not readable
f = open('files/诗1.txt', 'a')
# 'x'
# f = open('./files/词3.txt', 'x') # FileExistsError: [Errno 17] File exists: './files/词3.txt'
# f.write('你好吗?')
# f.read() # io.UnsupportedOperation: not readable
控制数据类型
f = open('files/词.txt', 'rt')
content = f.read()
print(type(content)) # <class 'str'>
f = open('files/词.txt', 'rb')
content = f.read()
print(type(content)) # <class 'bytes'>
f = open('files/poem.txt', 'tw')
f.write('你好吗?')
f = open('files/poem.txt', 'bw')
# f.write('你好吗?') # TypeError: a bytes-like object is required, not 'str'
f.write('hello, 你好吗?'.encode())
f = open('files/0.png', 'rb')
f.read()
读文件
1)文件对象.read() - 从文件读写位置开始,读到文件结束(以读的形式打开文件文件读写位置在文件开头)
f = open('files/词.txt')
content = f.read()
print(content)
文件对象.seek(偏移量) - 将读写位置移动到离文件开头指定距离所在的位置(一般设置为0,让读写位置回到文件开头)
f.seek(0)
content = f.read()
print(content)
2)文件对象.readline() - 读一行(从读写位置开始到一行结束)
f = open('files/词.txt', encoding='utf-8')
print('============================================')
line = f.readline()
print(line)
print('============================================')
line = f.readline()
print(line)
3)文件对象.readlines()
print('============================================')
f = open('files/词.txt', encoding='utf-8')
print(f.readlines())
练习:一行一行的读,将整个文件的内容读完
print('=======================练习=====================')
f = open('files/词.txt', encoding='utf-8')
while True:
line = f.readline()
if not line:
break
print(line[:-1])
写文件
1)文件对象.write(内容)
f = open('files/poem2.txt', 'a', encoding='utf-8')
f.write('你好')
f.writelines(['张三\n', '李四\n'])
关闭文件
文件对象.close() - 关闭指定文件
f.close()
# f.write('hello') # ValueError: I/O operation on closed file.
二、文件域
1.文件域 - 文件对象的作用范围
通过with open 打开文件,能够让被打开的文件对象自带作用范围,不需要手动关闭文件。
with open(file, mode=‘r’,…,encoding=None) as 文件对象:
文件的作用域
with open('files/词.txt', encoding='utf-8') as f:
print(f.read())
# print(f.read()) # ValueError: I/O operation on closed file.
三、数据持久化
1.数据持久化
程序中的数据默认都是保存在运行内容中的,当程序运算结束后全部都会销毁。
数据持久化是将数据保存在文件中(文件是保存在硬盘中,硬盘里面的数据除非手动操作或者硬盘损坏或者格式化,否则是不会销毁的)
2.什么时候需要做数据持久化
如果希望这次运行程序产生的数据,在一下次运行程序的时候还能用,那么这个时候就需要对这个数据进行持久化
3.怎么做持久化
满足以下3点数据就能持久化:
a. 用一个文件来保存对应的数据
b. 程序中需要这个数据的时候从文件中读出这个数据而不是在程序中直接给值
c. 数据发生了改变,要将最新的数据更新到文件中
b.程序中需要这个数据的时候从文件中读出这个数据而不是在程序中直接给值
with open('files/num.txt', encoding='utf-8') as f:
num = int(f.read())
修改数据
num += 1
c.数据发生了改变,要将最新的数据更新到文件中
with open('files/num.txt', 'w', encoding='utf-8') as f:
f.write(str(num))
print('次数:', num)
四、csv文件的操作
1.什么是CSV文件
csv是一种用逗号将一行数据隔开的文本文件,这种文件可以用表格来打开。多用于数据处理中数据的提供和保存
2.Python中怎么操作CSV文件
Python的标准库中有一个csv库,专门用来提供和csv文件操作相关功能
1)写数据
a.创建writer方式1
写对象 = csv.writer(csv文件对象)
写对象.writerow(元素是一行内容的列表)
写对象.writerows(元素是列表的列表)
b.创建writer方式2
1)csv文件的写操作方式1 - 以列表的形式写入数据
with open('files/学生信息.csv', 'w', encoding='utf-8', newline='') as f:
# a.写入数据
# 创建writer
writer = csv.writer(f)
# 写入一行内容
writer.writerow(['姓名', '成绩', '年龄'])
# 同时写入多行内容
writer.writerows([
['张三', 90, 28],
['李四', 76, 23],
['小明', 100, 18]
])
with open('files/学生信息.csv', 'a', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerows([
['老王', 88, 24],
['熊大', 91, 22]
])
2)csv文件的写操作方式2 - 以字典的形式写入数据
with open('files/商品信息.csv', 'w', newline='', encoding='utf-8') as f:
# 创建writer
# csv.DictWriter(文件对象, 字段名列表)
writer = csv.DictWriter(f, ['name', 'price', 'count'])
# 单独添加头部数据(将字段名列表中的元素作为第一行的数据写入文件中)
# writer.writeheader()
writer.writerow({'name': '商品名称', 'price': '商品单价', 'count': '商品库存'})
# 添加一条其他的数据
writer.writerow({'name': '鞋子', 'price': 300, 'count': 100})
# 同时添加多条其他的数据
writer.writerows([
{'name': '衣服', 'price': 85, 'count': 300},
{'name': '帽子', 'price': 34, 'count': 230},
{'name': '包', 'price': 500, 'count': 50}
])
五、csv文件的读操作
1.以列表的形式读数据
with open('files/商品信息.csv', newline='', encoding='utf-8') as f:
# 获取文件中的内容,返回值reader本质就是一个迭代器,迭代器中的元素是每一行内容对应的列表
reader = csv.reader(f)
# a.一行一行的获取数据
# # 单独取出第一行的数据
# next(reader)
#
# # 遍历其他行的数据
# for x in reader:
# print('x:', x)
# b.同时获取所有数据
data = list(reader)
print(data)
2.以字典的形式的读数据
with open('files/商品信息.csv', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
# # 直接获取第一行数据对应的列表
# print(reader.fieldnames) # ['商品名称', '商品单价', '商品库存']
#
# # 遍历获取每一行数据对应的字典(需要将元素转换成字典)
# for x in reader:
# print('x:', dict(x))
# print(list(reader))
new_reader = list(map(lambda item: dict(item), reader))
print(new_reader)
all_name = list(map(lambda item: item['商品名称'], new_reader))
print(all_name)
六、json数据
1.什么是json
json是一种特殊的文本数据格式,绝大部分编程语言都支持这种格式的数据的处理。一般在不同语言的程序之间进行数据交流的时候,数据的格式都是json格式。
2.json格式
json格式的数据要求: 1) 一个json有且只有一个数据 2) 唯一的这个数据必须是json支持的数据类型的数据
json支持的数据类型和表示方式:
数字类型 - 所有的数字,表示的时候直接写(支持科学计数法): 100, -100, 23.45, 3e4
字符串 - 所有的文本数据, 需要使用双引号引起来:“你好”, “hello”, “abc\n123”, “\u4e00”
布尔类型 - 只有 true 和 false 两个值
数组类型 - [元素1, 元素2, 元素3,…]
字典类型 - {键1:值1, 键2:值2, …} (键必须是字符串)
空值 - null(相当于Python中的None)
3.python数据和json之间的相互转换
python标准库中提供一个json模块,专门用来解决python中json数据的处理
- python 转 json
int/float 数字
字符串 双引号字符串
布尔值 True->true, False->false
None null
列表、元组 数组
字典 字典
json.dumps(python数据) - 将指定的python数据转换成对应的json格式的字符串(字符串的内容符合json格式的要求的字符串就是json格式的字符串)
- json 转 python
数字 int/float
字符串 字符串(引号会变成单引号)
布尔值 true->True, false->False
null None
数组 列表
字典 字典
json.loads(json格式的字符串) - 将json格式字符串中的数据转换成相应python类型的数据
import json
# 1.=============python转json=================
num = 48
num_json = json.dumps(num)
print([num_json]) # '48'
str1 = 'hello,json'
str1_json = json.dumps(str1)
print([str1_json]) # '"hello,json"'
print([json.dumps(True)]) # 'true'
print([json.dumps([1, 10, 'abc', True, False, None])]) # '[1, 10, "abc", true, false, null]'
tuple1 = (1, 10, 'abc', True, False, None)
print([json.dumps(tuple1)]) # '[1, 10, "abc", true, false, null]'
print([json.dumps({'name': 'xiaoming', 10: 20, 'gender': False})]) # '{"name": "xiaoming", "10": 20, "gender": false}'
# 2.===================json转Python=================
result = json.loads('"abc"')
print([result]) # 'abc'
result = json.loads('235')
print([result]) # 235
result = json.loads('[10, "abc", true, null]')
print([result]) # [10, 'abc', True, None]
json_str = '''{
"msg": "sucess",
"code": 200,
"goodsList":[
{"name": "衬衣", "price": 125.5, "count": 2}
]
}
'''
result = json.loads(json_str)
print(result, type(result))
print(result['goodsList'][0]['price']) # 125.5