文件操作模式

内容概要

  • 读写模式之a模式
  • 文件操作的相关方法
  • 文件操作模式
  • 文件内的光标移动及文件修改
  • 注册登入练习

读写模式之a模式

  • a模式 只追加模式

  • 路径不存在自动创建
    with open(r'c.txt', 'a', encoding='utf8') as s:
    pass
    image

  • 路径存在:不会删除文件内容,在文件末尾添加内容
    with open(r'c.txt', 'a', encoding='utf8') as d:
    d.write('\n嘿嘿嘿')
    image

    image

  • 我们所学的r,w,a读写模式只能操作文本文件

文件操作方法

  • 读系列
    with open(r'c.txt', 'r', encoding='utf8') as f:
    print(f.read()) # 一次性读取文件所有的内容
    image
    with open(r'c.txt', 'r', encoding='utf8') as f:
    print(f.readline()) # 每次只读取文件一行内容
    image
    with open(r'c.txt', 'r', encoding='utf8') as f:
    print(f.readlines()) # 读取文件所有的内容,组织成列表,每个元素是文件的每行内容
    image
    with open(r'c.txt', 'r', encoding='utf8') as f:
    print(f.readable()) # 判断当前文件是否有读的能力
    image

  • 写系列
    with open(r'c.txt', 'w', encoding='utf8') as a:
    a.write('哈哈哈') # 往文件内写入文本内容
    image
    with open(r'c.txt', 'w', encoding='utf8') as a:
    a.write(123) # 写入的必须是字符串类型
    image
    with open(r'c.txt', 'w', encoding='utf8') as a:
    a.writelines(['name', 'age', 'hobby']) # 可以将列表的多个元素写入
    image
    with open(r'c.txt', 'w', encoding='utf8') as a:
    print(a.writable()) # 判断当前文件是否有写的能力
    image
    with open(r'c.txt', 'w', encoding='utf8') as a:
    print(a.readable()) # 判断当前文件是否有读的能力
    image
    f.flush() # 直接将内存内文件数据刷到硬盘,相当于ctrl + s

文件优化操作

  • with open(r'c.txt', 'r', encoding='utf8') as f:
    print(f.read()) # 一次性读取文件所有的内容
    print(f.read()) # 一次性读取文件所有的内容
    print(f.read()) # 一次性读取文件所有的内容
    1.一次性读完之后,光标停在了文件末尾,无法再次读取内容
    2.该方法在读取大文件时,可能会造成内存溢出的情况
    解决上述问题的策略就是逐行读取文件内容
    for line in f: # 文件变量名f支持for循环,相当于一行行读取文件内容
    以后涉及到多行文件内容的情况一般都是用for循环读取

文件操作模式

  • t 文本模式
    1.默认的模式
    r w a ---rt wt at
    2.该模式所有操作都是以字符串基本单位(文本)
    3.该模式必须要指定encoding参数
    4.该模式只能操作文本文件

  • b 二进制模式
    1.该模式可以操作任意类型的文件
    2.该模式所有操作都是以bytes类型(二进制)基本单位
    3.该模式不需要指定encoding参数
    rb wb ab
    image

注册登入

  • while True:
    print('''
    0.退出
    1.用户注册
    2.用户登入
    ''')
    d = input('输入你想执行的编号: ').strip()
    d = int(d)
    if d == 1:
    print('用户注册')
    username = input('user: ').strip()
    password = input('pass: ').strip()
    s = '%s|%s\n' % (username, password)
    with open(r'c.txt', 'r', encoding='utf8') as f:
    for line in f:
    name1, password1 = line.split('|')
    if name1 == username:
    print('用户名已存在')
    break
    else:
    with open(r'c.txt', 'a', encoding='utf8') as f1:
    f1.write(s)
    print('用户%s注册成功' % username)
    elif d == 2:
    print('用户登入')
    username = input('user: ').strip()
    password = input('pass: ').strip()
    with open(r'c.txt', 'r', encoding='utf8') as z:
    for line in z:
    name1, password1 = line.split('|')
    if username == name1 and password == password1.strip():
    print('登入成功')
    break
    else:
    print('用户民或密码错误')
    elif d == 0:
    print('再见')
    break
    else:
    print('抱歉,没有该功能')
    image

image

posted @ 2021-11-11 16:17  一览如画  阅读(76)  评论(0)    收藏  举报