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

Python Note — Day 9. 文件操作

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

Python Note — Day 9. 文件操作

15 文件操作

针对磁盘中文件的读写,文件I/O

  • 文件操作步骤:
    1.打开文件 2.读写文件 3.关闭文件
  • 写入文件的操作:(把大象装进冰箱)
    1.打开文件 open()
    2.写入内容 write()
    3.关闭文件 close()
  • 读取文件的操作:(把大象从冰箱取出)
    1.打开文件 open()
    2.读取内容 read()
    3.关闭文件 close()
15.1 文件的基础操作

1.open()
格式:open(文件的路径,打开方式,[字符集])

  • 路径 url 统一资源定位符
    • 相对路径: 针对文件的表示:
      1.txt ==> 具体文件前没有任何表示时,默认为当前目录中的1.txt
      ./1.txt ==> 代表当前目录中的1.txt
      ../1.txt ==> 代表当前目录中的上一级目录中的1.txt
      ../a/b/1.txt ==> 代表当前目录中的a目录中的b目录中的1.txt
    • 绝对路径:
      windows: c:/users/appdata/1.txt
      linux: /user/home/yc/1.txt
  • 打开方式:
    基础模式: w r x a
    • w 模式:write 写入
      1.文件如果不存在,则创建文件
      2.文件如果存在,则打开文件,并且清空文件内容
      3.文件打开后,文件指针在文件最前面
    • r 模式:read
      1.若文件不存在,报错
      2.文件存在,则打开文件
      3.文件指针在文件最前面
    • x 模式:xor 异或 1.文件不存在,则创建 2.文件存在,报错(防止覆盖) 3.文件指针在文件最前面
    • a 模式: append() 追加
      1.文件不存在,则创建
      2.文件存在,则打开 (和w模式区别,文件打开后不会清空)
      3.文件指针在文件最后
    • 扩展模式:
      1.b模式 bytes 二进制
      2.+模式 plus 增强模式(可读可写)
  • encoding 可选参数,设置文件的字符集
    如果是一个二进制文件,则不需要设置字符集
    encoding='utf-8'
# 1.打开文件,创建了一个文件对象
fp = open('./1.txt','w',encoding='utf-8')
print(fp,type(fp))

# 2.写入内容
# 使用文件对象,调用write(),写入
fp.write('hello world')

# 3.关闭
fp.close()

# 2.读取内容
# 使用文件对象,调用read()
res = fp.read()
print(res)

文件操作模式的组合:
w,r,a,x
wb,rb,ab,xb
w+,r+,a+,x+
wb+,rb+,ab+,xb+

15.2 打开模式的演示操作

文件操作的高级写法

'''
with open(文件路径,打开模式) as 变量:
    变量.操作()
'''
with open('./1.txt','r+',encoding='utf-8') as fp:
    rs = fp.read()
    print(rs)
    fp.write(rs)
  • r+ 模式是可读可写
  • w+ 模式也是可读可写,但是w模式的特点是打开之后直接清空文件
  • a+ 模式 追加写,但光标在最后读不到内容
  • x+ 异或
with open('./2.txt','x+',encoding='utf-8') as fp:
    rs = fp.write('my headache')
    re = fp.read()    # 读不到,写入后,光标在最后
    print(re)
15.3 文件操作相关函数
  • 2.write(字符串)
    • writelines(容器类型)
      注意:容器类型必须是可写入的字符串
aa='exaggerate'
aa = ['one','two']
aa = {'name':'ll','age':'20'}   # 只能写入key
with open('./1.txt','w',encoding='utf-8') as fp:
    fp.writelines(aa)
  • 3.read()
    格式:文件对象.read() 从当前指针读到最后
    格式:文件对象.read(读取的字节数) 可以读取指定长度的字符
    • readline() 一次只能读取一行,光标移动
    • readline(int) 可以读取当前行指定的字节数,超过则读取整行
    • readlines() 一次读取多行,每行作为一个元素,返回一个列表
    • readlines(hint) 按照行进行读取hint字节数,多进少补,不够一行按一行算
with open('./1.txt','r',encoding='utf-8') as fp:
    res = fp.readline()
    print(res)
    res = fp.readline()
    print(res)
                        '''
                        once upon a time
                        
                        there is a lovely '''
with open('./1.txt','r',encoding='utf-8') as fp:
    # res = fp.readlines()  # ['once upon a timen', 'there is a lovely n', 'rabbitn', 'livingn', 'in the forest']

    # res = fp.readlines(16)   # ['once upon a timen']
    res = fp.readlines(17)     # ['once upon a timen', 'there is a lovely n']
    print(res)
  • 4.seek()
    seek(self,offset,whence = 0) 设置指针的位置,字节
    offset : 指针偏移量
    whence : 指针所在位置,0:指针在文首;1:指针当前位置;2:文末
with open('./1.txt','a+',encoding='utf-8') as fp:
    # a+ 模式 指针默认在文件最后,直接读取是读不到内容的
    fp.seek(0)  # 指针设置在文件开头
    fp.seek(4)
    res = fp.read()
    print(res)

with open('./1.txt','r+',encoding='utf-8') as fp:
    # r+ 模式 指针在开头
    fp.seek(0,2)  # 指针设置在文件末尾
  • 5.truncate(size) 截断文件内容并更新文件
    默认从文件首行的首个字符开始,截断长度为size个字节数
    size为0,则直接从当前位置截断到最后
with open('./1.txt','r+',encoding='utf-8') as fp:
    fp.truncate(56)
15.3 文件操作 练习题

1.使用数据写入文件的方式,完成一个注册和登录
实现功能:
用户输入用户名和密码以及确认密码
用户名不能重复,密码长度大于3
两次密码要一致
可以用已经注册的账户登录
密码如果错误3次,则锁定,不能登录

提示:
strip() !!!
split() !!!
封装函数
在1.txt没创建时 r 模式会报错,采用 a+模式,同时设置指针在文首
登录时检测用户名是否存在
获取用户名在用户列表的索引位置
inx = userlist.index(name)
if pwd == pwdlist[inx]
检测用户是否属于锁定状态,判断用户是否在黑名单中
判断当前脚本是否作为一个主进程脚本在执行:

if __name__=='__main__':  
  这里的代码,只有在使用python解释器直接运行时才执行  
  如果当前的脚本,作为一个模块被其他文件都如后使用,那么这个地方的代码不会执行
  因此这个地方的代码,适合写当前脚本中的一些测试,这样不会影响其他脚本
  pass
def register():
    while True:
        name = input('please set username : ')
        userlist = []
        with open('./1.txt','r',encoding='utf-8') as fp:
            res = fp.readlines()
        for i in res:
            re = i.strip('n')
            rr = list(re.split(':'))
            userlist.append(rr[0])
        if name not in userlist:
            break
        else:
            print('username already exists ! ')
    while True:
        pwd = input ('please set password : ')
        if len(pwd) > 3:
            break
        else:
            print('please set number more than 3 digits !')
    while True:
        pwd1 = input('please repeat password : ')
        if pwd == pwd1:
            info = f'{name}:{pwd}n'
            with open('./1.txt','a',encoding='utf-8') as fp:
                fp.write(info)
            print('register success !')
            break
        else:
            print('second time is different !')
def login():
    name = input('please enter username : ')
    count = 1
    with open('./1.txt', 'r', encoding='utf-8') as fp:
        res = fp.readlines()
    test = f'{name} is lockn'
    if test in res:
        print('ur account is locked ! please contact manager !')
    else:
        while count < 4:
            pwd = input('please enter ur password : ')
            use = f'{name}:{pwd}n'
            if use in res:
                print('login success !')
                break
            else:
                print(f'wrong code ! {3-count} times left !')
                count += 1
                lock = f'{name} is lockn'
                with open('./1.txt', 'a', encoding='utf-8') as fp:
                    fp.write(lock)
    if count == 4 :
        print('ur account is locked ! please contact manager !')
while True:
    n = input('please enter 1 to login or enter 2 to register : ')
    if n == '1':
        login()
        break
    elif n =='2':
        register()
        break
    else:
        print('wrong !')

老师版

userlist = []
pwdlist = []

def readuserlist():
    # 在1.txt没创建时 r 模式会报错,采用 a+模式,同时设置指针在文首
    with open('./1.txt','a+',encoding='utf-8') as fp:
        fp.seek(0)
        res = fp.readlines()
        for i in res:
            re = i.strip('n')
            rr = list(re.split(':'))
            userlist.append(rr[0])
            pwdlist.append(rr[1])
    with open('./blacklist.txt','a+',encoding='utf-8') as fp:
        fp.seek(0)
        blacklist = fp.readlines()

def register():
    while True:
        name = input('please set username : ')
        if name not in userlist:
            while True:
                pwd = input('please set password : ')
                if len(pwd) > 3:
                    while True:
                        pwd1 = input('please repeat password : ')
                        if pwd == pwd1:
                            info = f'{name}:{pwd}n'
                            with open('./1.txt', 'a', encoding='utf-8') as fp:
                                fp.write(info)
                            print('register success !')
                            break
                        else:
                            print('second time is different !')
                    break
                else:
                    print('please set number more than 3 digits !')
            break
        else:
            print('username already exists ! ')

def login():
    while True:
        name = input('please enter username : ')
        errnum = 3
        if name in userlist:
            test = f'{name}n'
            if test in blacklist:
                print('ur account is locked ! please contact manager !')
            else:
                while errnum >0:
                    pwd = input('please enter ur password : ')
                    use = f'{name}:{pwd}n'
                    if use in res:
                        print('login success !')
                        break
                    else:
                        errnum -= 1   # 注意注意!!
                        if errnum == 0:
                            print('ur account is locked ! please contact manager !')
                            with open('./blacklist.txt', 'a', encoding='utf-8') as fp:
                                fp.write(name+'n')
                        else:
                            print(f'wrong code ! {errnum} times left !')
            break
        else:
            print('wrong user !')

if __name__=='__main__':
    while True:
        n = input('please enter 1 to login or enter 2 to register : ')
        if n == '1':
            login()
            break
        elif n =='2':
            register()
            break
        else:
            print('wrong !')
  • 扩展:可以实现购物,定义一些商品和价格,用户有100元,完成购物扣款
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/294640.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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