python基础---文件基本操作(20)

0、文件与文件模式介绍

1、什么是文件
文件是操作系统提供给用户/应用程序操作硬盘的一种虚拟的概念/接口

用户/应用程序(open())
操作系统(文件)
计算机硬件(硬盘)

2、为何要用文件

	用户/应用程序可以通过文件将数据永久保存在硬盘中
	即操作文件就是操作硬盘

    用户/应用程序直接操作的是文件,对文件进行的所有的操作,
    都是在向操作系统发送系统调用,然后再由操作将其转换成具体的硬盘操作

3、如何用文件:open()

    控制文件读写内容的模式:t和b
        强调:t和b不能单独使用,必须跟r/w/a连用
            t文本(默认的模式)
                1、读写都以str(unicode)为单位
                2、文本文件
                3、必须指定encoding='utf-8'

        b二进制/bytes
    控制文件读写操作的模式
        r只读模式
        w只写模式
        a只追加写模式
        +:r+、w+、a+

1、打开文件

Windows路径分隔符问题

  • 解决方案一:推荐

    open(r'C:\a\ad\c.txt')
    
  • 解决方案二:

     open('C:/a/ad/c.txt')
    

Linux环境下

open('/a/ad/c.txt')

2、如何用文件:open()

控制文件读写内容的模式:t和b
强调:t和b不能单独使用,必须跟r/w/a连用
t文本(默认的模式)

  • 读写都以str(unicode)为单位
  • 文本文件
  • 必须指定encoding=‘utf-8’
f = open(r'a.txt', mode='rt')  # f的值是一种变量,占用的是应用程序的内存空间
 print(f)

3、操作文件

读/写文件,应用程序对文件的读写请求都是在向操作系统发送系统调用,然后由操作系统控制硬盘把输入读入内存、或者写入硬盘

f = open(r'a.txt', mode='rt')
res = f.read()
print(res)

4、关闭文件

f.close()  # 回收操作系统资源
del f  # 回收应用程序资源

5、with上下文管理

文件对象又称文件句柄

  • 方式一:一次打开一个文件

    with open(r'a.txt', mode='rt') as f1:
        res = f1.read()
        print(res)
    
  • 方式二:一次打开两个文件或多个文件

    with open('a.txt') as f1,  open('b.txt') as f2:
        res1 = f1.read()
        res2 = f2.read()
        print(res2)
        print(res1)
    

6、指定字符编码

没有指定encoding参数操作系统会使用自己默认的编码

  • Linux系统默认utf-8
  • windows系统默认gbk
'''
如何用文件:open()
    控制文件读写内容的模式:t和b
        强调:t和b不能单独使用,必须跟r/w/a连用
            t文本(默认的模式)
                1、读写都以str(unicode)为单位
                2、文本文件
                3、必须指定encoding='utf-8'
'''
with open('a.txt', mode='rt',encoding='utf-8') as f:
    res = f.read()
    print(res, type(res))

7、以t模式为基础进行内存操作

7.1 r模式(默认的操作模式)

r(默认的操作模式):只读模式,当文件不存在时,当文件存在时文件指针跳到开始位置

with open('a.txt', mode='rt', encoding='utf-8') as f:
    print('第一次读'.center(50,'*'))
    res = f.read()  # 把所有内容从硬盘读入内存
    print(res)

    print('第二次读'.center(50,'*'))
    res = f.read()  # 把所有内容从硬盘读入内存
    print(res)

案例:从一个user.txt文件中读出来,比对与用户输入的是否一致

  • 方式一:一次读一行
    inp_usrname = input('your name:').strip()
    inp_password = input('your password:').strip()
    
    # 验证
    with open('user.txt', mode='rt',encoding='utf-8') as f:
        for line in f:
            username,password = line.strip('\n').split(':')
            if inp_password == password and inp_usrname == username:
                print('login successful')
                break
        else:
            print('username or password error')
    
  • 方式二:把文件里的内容都读出来
    inp_usrname = input('your name:').strip()
    inp_password = input('your password:').strip()
    
    with open('user.txt', mode='rt',encoding='utf-8') as f:
        res = f.read()
        username, password = res.split(':')
    if inp_password == password and inp_usrname == username:
        print('login successful')
    else:
        print('username or password error')
    

7.2 w模式

w:只写模式,当文件不存在时会创建空文件,当文件存在时会清空文件,指针位于开始位置

with open('d.txt',mode='wt', encoding='utf-8') as f:
    # f.read()  # 不可读
    f.write('哈哈哈\n')

  • 强调1:在以w模式打开文件没有关闭的情况下,连续写入,新写的内容总是跟在旧的之后

    with open('d.txt',mode='wt', encoding='utf-8') as f:
        f.write('哈哈哈1\n')
        f.write('哈哈哈2\n')
        f.write('哈哈哈3\n')
        f.write('哈哈哈4\n')
    
  • 强调2:如果重新以w模式打开文件,则会清空文件内容

with open('d.txt',mode='wt', encoding='utf-8') as f:
    f.write('哈哈哈1\n')
with open('d.txt', mode='wt', encoding='utf-8') as f:
    f.write('哈哈哈2\n')
with open('d.txt', mode='wt', encoding='utf-8') as f:
    f.write('哈哈哈3\n')
    f.write('哈哈哈4\n')

案例:w模式用来创建全新的文件
文件的copy工具

  • 方式一:一次性拷贝内容
src_file = input('源文件路径:').strip()
dst_file = input('新文件路径:').strip()
with open(r'{}'.format(src_file), mode='rt', encoding='utf-8') as f1,\
    open(r'{}'.format(dst_file), mode='wt', encoding='utf-8') as f2:
    res = f1.read()
    f2.write(res)
  • 方式二:按行拷贝内容
src_file = input('源文件路径:').strip()
dst_file = input('新文件路径:').strip()
with open(r'{}'.format(src_file), mode='rt', encoding='utf-8') as f1,\
    open(r'{}'.format(dst_file), mode='wt', encoding='utf-8') as f2:
    for line in f1:
       f2.write(line)  

7.3 a模式

a:只追加写,在文件不存在时会创建空文档,在文件存在时文件指针会直接跳到末尾

with open('e.txt', mode='at', encoding='utf-8') as f:
    # f.read()  # 报错 不能读
    f.write('你好!\n')
    f.write('我是!\n')
    f.write('男人!\n')

案例:a模式用来在原有的文件内存的基础上写入新的内容,比如记录日志,注册
注册功能:

name = input("用户名:")
pwd = input("密码:")
with open('db.txt', mode='at', encoding='utf-8') as f:
    f.write('{}:{}\n'.format(name,pwd))

7.4 w模式与a模式的异同

  • 相同点:在打开的文件不关闭的情况下,连续的写入,新写的内容总会跟在前写的内容之后
  • 不同点:以a模式重新打开文件,不会清空原文件内容,会将文件指针直接移动到文件末尾,在末尾写入新内容

7.5 +模式

了解 :+不能单独使用,必须配合r、w、a

with open('f.txt', mode='rt+', encoding='utf-8') as f:
    print(f.read())
    f.write('牛逼')

with open('f.txt', mode='wt+', encoding='utf-8') as f:
    f.write('111\n')
    f.write('牛逼')
    print(f.read())

with open('f.txt', mode='a+t', encoding='utf-8') as f:
    f.write('111\n')
    f.write('牛逼')
    print(f.read())
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值