栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文件基本操作
  • 1、打开文件
  • 2、如何用文件:open()
  • 3、操作文件
  • 4、关闭文件
  • 5、with上下文管理
  • 6、指定字符编码
  • 7、以t模式为基础进行内存操作
    • 7.1 r模式(默认的操作模式)
    • 7.2 w模式
    • 7.3 a模式
    • 7.4 w模式与a模式的异同
    • 7.5 +模式

1、打开文件

Windows路径分隔符问题

  • 解决方案一:推荐

    open(r'C:aadc.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('哈哈哈1n')
        f.write('哈哈哈2n')
        f.write('哈哈哈3n')
        f.write('哈哈哈4n')
    
  • 强调2:如果重新以w模式打开文件,则会清空文件内容

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

案例: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('111n')
    f.write('牛逼')
    print(f.read())

with open('f.txt', mode='a+t', encoding='utf-8') as f:
    f.write('111n')
    f.write('牛逼')
    print(f.read())
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1018195.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号