15-Python文件相关操作

1.文件操作

1.1 计算机数据的存储

计算机的存储系统分为 运行内存 和 硬盘 两种:
运行内存:用来保存程序运行过程中产生的数据,程序运行结束后会自动销毁
硬盘: 硬盘是用来保存文件的,保存在文件中的数据就是保存在硬盘中的。除非手动删除,否则数据会一直存在

1.2 数据持久化

数据持久化就是讲数据以各种形式保存到硬盘中(保存到本地文件中)

1.3 文件操作

文件操作基本步骤:打开文件 -> 操作文件(读、写) -> 关闭文件

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()

2.文件的读写操作

2.1 打开文件

打开文件方式一:
文件对象 = 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.

2.2 文件读操作

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() - 一行一行的读,读完为止。返回的是一个列表,列表中的元素是每一行的内容

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)

read_file('files/text.txt')

2.3 写操作

文件对象.write(内容)

with open('files/text.txt', 'a', encoding='utf-8') as f:
    f.write('\n春眠不觉晓')

3.数据持久化

3.1 数据持久化的基本操作

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()

4. 字典和列表的数据持久化

# 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()

5.json数据

import json

5.1 什么是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)

5.2 json转python

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)

5.3 python转json

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值