文件操作相关内容

一、文件操作

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

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

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

打开文件
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.打开文件
“”"
打开文件方式一:
文件对象 = 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)文件对象.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.写操作

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

三、程序持久化

1.数据持久化的基本操作
“”"
数据保存在文件中
需要数据的时候从文件中去读数据
当数据发生改变的时候,对保存数据的文件进行更新
“”"""
#注意:如果以读的方式打开一个不存在的文件,程序会报错,如果是以写的方式打开一个不存在的文件,不会报错并且会自动新建这个文件

#练习:写一个程序统计这个程序启动的次数

#思考:写程序实现添加学生的功能,要求每次运行程序添加的学生,下次还在
```python
with open('files\stud', 'a', encoding='utf-8') as f:
    name = input('请输入学生姓名')
    name1 = f.write(name + '\n')
with open('files\stud', encoding='utf-8') as f:
    print(f.read())

四、字典和列表的数据持久化

1.字典和列表的写操作:先将列表或者字典转换成字符串
def add_student():
    name = input('姓名')
    age = input('年龄')
    tel = input('电话')# 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.字典和列表的读操作:将容器格式的字符串转换成对应的容器型数据类型(evalwith 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()


with open('files\stud', encoding='utf-8') as f:
    list1 = "[]"
    eval(f.read(list1))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值