文件操作
一、文件操作
1.计算机数据的存储
1 2 3 4 5 | """ 计算机的存储系统分为 运行内存 和 硬盘 两种: 运行内存:用来保存程序运行过程中产生的数据,程序运行结束后会自动销毁 硬盘: 硬盘是用来保存文件的,保存在文件中的数据就是保存在硬盘中的。除非手动删除,否则数据会一直存在 """ |
2.数据持久化
1 2 3 | """ 数据持久化就是讲数据以各种形式保存到硬盘中(保存到本地文件中) """ |
3.文件操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | """ 文件操作基本步骤:打开文件 -> 操作文件(读、写) -> 关闭文件 """ # 1)打开文件 """ open(file, mode='r', encoding=None) - 以指定的模式打开指定文件并且返回一个文件对象 说明: a. file - 文件路径,字符串类型 绝对路径:文件/文件夹的全路径 (一般不写绝对路径) 相对路径:只写文件绝对路径的一部分,另外一部分用特殊符号代替 ./ - 表示当前目录(当前写代码的文件所在的文件夹), 可以省略 ../ - 表示当前目录的上层目录 .../ - - 表示当前目录的上层目录的上层目录 ..../ ...../ """ # 绝对路径 open(r'/Users/yuting/授课/python2002/01语言基础/day14-文件操作/files/text.txt') # 相对路径: ./ open('./files/text.txt') open('./text2.txt') open('files/text.txt') # 相对路径:../ open('../day14-文件操作/files/text.txt') """ b. mode - 打开方式,字符串类型 第一组:控制操作类型 r - 以只读的方式打开文件(默认值) w - 以只写的方式打开文件(打开前会先清空原文件中的内容) a - 以只写的方式打开文件; 第二组:控制数据类型(文本-str/二进制数据-bytes) t - 操作的数据是文本数据(默认) b - 操作的数据是二进制数据 注意:每一组值只选一个,两组值进行组合使用 """ # 情况一:r、rt # f = open('files/text.txt', 'rt') # content = f.read() # # f.write('abc') # io.UnsupportedOperation: not writable # print(content) # print(type(content)) # <class 'str'> # 情况二:rb # f = open('files/text.txt', 'rb') # content = f.read() # print(content) # print(type(content)) # <class 'bytes'> # 情况三:wt # f = open('files/text.txt', 'w') # # f.read() # io.UnsupportedOperation: not readable # f.write('abc123') # 情况四:at # f = open('files/text.txt', 'a') # # f.read() # io.UnsupportedOperation: not readable # f.write('你好吗?') # 情况五:wb f = open('files/text.txt', 'wb') f.write(b'how are you!') # TypeError: a bytes-like object is required, not 'str' f.write(bytes('你好!', encoding='utf-8')) """ c. encoding - 文本编码方式; 直接写 'utf-8' 注意:如果打开方式中带 b , 不能设置 encoding """ # open('files/text.txt', 'rb', encoding='utf-8') # ValueError: binary mode doesn't take an encoding argument f = open('files/text.txt', 'r', encoding='utf-8') print(f.read()) # 总结:文本文件打开的时候可以是 t 也可以是 b; 二进制文件只能是 b 打开(图片文件、音视频文件等) f = open('files/image.jpg', 'rb') f.read() |
二、文件的读写操作
1.打开文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | """ 打开文件方式一: 文件对象 = open(文件路径, 文件打开方式, encoding=文本编码方式) 操作文件对象 文件对象.close() with open(文件路径, 文件打开方式, encoding=文本编码方式) as 文件对象: 操作文件对象 """ print('方式一:') f = open('files/text.txt', encoding='utf-8') print(f.read()) f.close() # print(f.read()) # ValueError: I/O operation on closed file. print('方式二:') with open('files/text.txt', encoding='utf-8') as f: print(f.read()) # print(f.read()) # ValueError: I/O operation on closed file. print('===============================') |
2.文件读操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | """ 1)文件对象.read() - 从文件读写位置开始,读到文件的结尾(默认情况下读写位置在文件开头) """ with open('files/text.txt', 'r', encoding='utf-8') as f: content = f.read() print('第一次:', content) content = f.read() print('第二次:', content) """ 2)文件对象.readline() - 读文本文件的一行内容(从当前读写位置读到一行结束) 3)文件对象.readlines() - 一行一行的读,读完为止。返回的是一个列表,列表中的元素是每一行的内容 """ print('==============================') with open('files/text.txt', encoding='utf-8') as f: content = f.readline() print(content) content = f.readline() print(content) # 练习:一行一行的读文件,读完为止 def read_file(file): with open(file, 'r', encoding='utf-8') as f: while True: c = f.readline() if not c: break print(c) print('========================') read_file('files/text.txt') |
3.写操作
1 2 3 4 5 | """ 文件对象.write(内容) """ with open('files/text.txt', 'a', encoding='utf-8') as f: f.write('\n春眠不觉晓') |
三、数据持久化的基本操作
1.数据持久化的基本操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | """ a. 数据保存在文件中 b. 需要数据的时候从文件中去读数据 c. 当数据发生改变的时候,对保存数据的文件进行更新 """ # 注意:如果以读的方式打开一个不存在的文件,程序会报错!如果是以写的方式打开一个不存在的文件,不会报错并且会自动新建这个文件 # open('files/text2.txt', 'r') # FileNotFoundError: [Errno 2] No such file or directory: 'files/text2.txt' open('files/text4.txt', 'a') # 练习:写一个程序统计这个程序启动的次数 with open('files/count', encoding='utf-8') as f: count = int(f.read()) count += 1 print(count) with open('files/count', 'w', encoding='utf-8') as f: f.write(str(count)) # 思考:写程序实现添加学生的功能,要求每次运行程序添加的学生,下次还在 def add_student(): name = input('姓名:') with open('files/students.txt', 'a', encoding='utf-8') as f: f.write(name+' ') with open('files/students.txt', encoding='utf-8') as f: print(f.read()) add_student() |
四、字典和列表的数据持久化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | # students = ['张三', '小明', '小花'] # students = [ # {'name': '张三', 'age': 18, 'tel': '110'}, # {'name': '小明', 'age': 20, 'tel': '120'}, # {'name': '小花', 'age': 21, 'tel': '119'} # ] # # # 1.字典和列表的写操作: 先将列表或者字典转换成字符串 # with open('files/students.txt', 'w', encoding='utf-8') as f: # f.write(str(students)) # # # 2.字典和列表的读操作:将容器格式的字符串转换成对应的容器型数据类型(eval) # with open('files/students.txt', 'r', encoding='utf-8') as f: # content = f.read() # print(content) # print(type(content)) # new_content = eval(content) # print(new_content) # print(type(new_content)) # for item in new_content: # print(item) # print(type(item)) def add_student(): name = input('姓名:') age = input('年龄:') tel = input('电话:') stu = {'name': name, 'age': age, 'tel': tel} with open('files/students.txt', 'r', encoding='utf-8') as f: all_students = eval(f.read()) all_students.append(stu) with open('files/students.txt', 'w', encoding='utf-8') as f: f.write(str(all_students)) print(all_students) add_student() |
五、json数据
1.什么是json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import json """ 1)存在的意义 json就是不同编程语言之间进行数据交流的一种通用格式 2)概念 json是一种数据格式:a.一个json有且只有一个数据 b.这个数据是json支持的数据类型的数据 3)json支持的数据类型: 数字类型、字符串、布尔、数组、字典/对象、null(空值) a.数字类型: 所有的数字(19, 90, 802, -23,0.34,3e4) b.字符串:用双引号引起来的文本数据(支持转义字符) - 必须是双引号 c.布尔: 只有 true 和 false 两个值 d.数组: 相当于python的列表, [元素1, 元素2, 元素3,...] e.字典: 相当于Python的字典,{key1:value1, key2:value2,...} 注意:key只能是字符串 f.空值:null(相当于None) """ |
2.json转python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import json """ json python 数字类型 数字(int/float) 字符串 字符串(可能会将双引号变成单引号) 布尔 布尔(true->True, false -> False) 数组 列表 字典 字典 空值 null -> None json.loads(字符串) - 将json格式的字符串转换成python对应的数据。(这儿的字符串的内容必须满足json格式) """ # json.loads('abc') # 报错:json.decoder.JSONDecodeError result = json.loads('"abc"') print(type(result), result) result = json.loads('true') print(result) result = json.loads('[100, "abc", true, null]') print(result) |
3.python转json
1 2 3 4 5 6 7 8 9 10 11 12 13 | """ python json int/float 数字 字符串 变成双引号的字符串 布尔 布尔(True->true, False->false) 列表/元组 数组 字典 字典 None null json.dumps(数据) - 将指定的python数据转换成json格式的字符串 """ result = json.dumps([100, 'abc', True, (10, 20), None]) print(type(result), result) |