Python文件

11 File

11.1 文件读写

针对磁盘中的文件的读写操作。文件I/O 输入(Input)/输出(Output)

写入文件操作:

  • 1.打开文件open()
  • 2.写入内容write()
  • 3.关闭文件close()

读取文件操作

  • 1.打开文件open()
  • 2.读取内容read()
  • 3.关闭文件close()

code:

# *****************************************************
"""
写入文件操作:
1.打开文件open()
    参数1:文件路径
        路径 url 统一资源定位符
        相对路径:在某某大厦的对面
            针对文件的相对路径表示:
                1.txt---具体文件前没有任何路径的表示,默认为当前目录 和./1.txt是同一个位置
                ./1.txt---./代表当前目录中的1.txt
                ../1.txt---../代表当前目录中的上一级目录中的1.txt
                ./a/b/c1.txt
        绝对路径:收货地址
            windows: c:/user/appdata/1.txt
            Linux: /user/home/yc/1.txt
    参数2:打开的方式
        基础模式:w r x a
            w模式:write 写入
                1.如果文件不存在,则创建文件
                2.如果文件存在,则打开文件,并且清空文件内容
                3.文件打开后,文件的指针在文件的最前面
            r模式:read 读取
                1.如果文件不存在,则报错---
                2.文件如果存在,则打开文件
                3.文件打开后,文件指针在文件的最前面
            x模式:异或模式
                1.如果文件不存在,则创建文件
                2.如果文件存在,则报错(防止覆盖)
                3.文件指针在文件最前面
            a模式:append模式 追加模式
                1.如果文件不存在,则创建
                2.如果文件存在,则打开文件(和w模式的区别在于,a模式不会清空文件)
                3.文件指针在当前文件最后
        扩展模式:b +
            b模式:bytes 二进制---使用二进制模式时不要写utf-8字符集
            +模式:plus 增强模式(可读可写)
        文件操作模式组合:
            w,r,a,x
            wb,rb,ab,xb
            w+,r+,a+,x+
            wb+,rb+,ab+,xb+
    参数3:encoding 可选参数---设置文件的字符集 ASCII UNICODE,如果是一个二进制的文件时,不需要设置字符集
        encoding='utf-8'
2.写入内容write()
3.关闭文件close()

读取文件操作
1.打开文件open()
2.读取内容read()
3.关闭文件close()

文件操作的高级写法:
    with open(文件路径,打开模式) as 变量:
        变量.操作()

设置指针位置:只能获取指针前面的内容,所以一些情况下需要设置指针
    fp.seek(0)---设置指针在文件最前面
"""
fp = open('./1.txt','r',encoding='utf-8')
print(f"fp = {fp},type(fp) = {type(fp)}")
print(f"fp.read() = {fp.read()}")
fp.close()
# 这种情况下之前文件的内容会被改写
with open('./1.txt','r+',encoding='utf-8') as fp1:
    fp1.write('Jasmine')
    fp1.seek(0)
    print(f"fp1.read() = {fp1.read()}")

运行结果:

E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_50file_read_and_write.py
fp = <_io.TextIOWrapper name='./1.txt' mode='r' encoding='utf-8'>,type(fp) = <class '_io.TextIOWrapper'>
fp.read() = Jasmineorld
fp1.read() = Jasmineorld

Process finished with exit code 0

11.2 文件相关函数

code:

# ***************************************************
"""
文件函数:
    open(文件路径,打开的方式,[字符集])---打开文件
    file.write(内容)---写入内容,内容只能是字符串
    file.read(读取的字节数)---默认参数为从指针位置读取到最后,可自定义设置读取的字节数
    file.close()---关闭打开的文件file
    file.writelines()---可以写入容器类型数据,但是容器类型的元素只能是字符串
    file.seek(loc,direation)---可以设置文件指针的位置为loc;direation=0时,设置为从文件开始向后偏移loc位置;
                               direation=1时,设置为从当前位置向后偏移loc位置;direation=2时,设置为从末尾位置向前偏移loc位置
    file.readline(读取的字节数)---读取一行文字,读取的字节数默认为一行数据的字节数,可以自定义读取的字节数
    file.readlines(hint)---不传递hint参数时读取所有数据,每一行作为一个元素,返回一个列表;
                           传递hint参数时,按字节数读取多行,如果读到最后一行时字节数不够,则完整读取最后一行
    file.truncate(data)---截断光标开始data字节数后面的内容,文件中保留的长度为data个字节数
"""

varstext = ['hello', 'world', '1', '2','\n']
varstext2 = {'name':'lily','sex':'girl','\n':'x'}
with open('./1.txt','a+',encoding='utf-8') as fp:
    fp.writelines(varstext)
    fp.writelines(varstext2)
with open('./1.txt','r',encoding='utf-8') as fp:
    # print(f"fp.read() = {fp.read()}") # 读取所有数据
    # print(f"fp.read(3) = {fp.read(3)}") # 中文也是算字及符号的个数
    # print(f"fp.readline() = {fp.readline()}",end='')
    # print(f"fp.readline(8) = {fp.readline(8)}")
    fp.seek(0,2)
    print(f"fp.readlines(30) = {fp.readlines(30)}")
with open('./1.txt','a+',encoding='utf-8') as fp:
    fp.truncate(5)
    print(f"fp.readlines(30) = {fp.readlines(30)}")

运行结果:这个依文件内容不同

E:\Programs_Way\Python\python.exe D:/Prj/Python/Study_Basic_Grammar/_51file_function.py
fp.readlines(30) = []
fp.readlines(30) = []

Process finished with exit code 0

11.3 账户注册和登录练习题

code:

# *************************************************************
"""
账户注册和登录练习题
判断当前的脚本是否作为一个主进程脚本在执行
if __name__ == '__main__':
    这里的代码,只有在使用python解释器直接运行时才执行
    如果当前的脚本,作为一个模块被其他脚本导入使用,那么这个地方的代码不会被执行
    因此这个地方的代码,适合写当前脚本中的一些测试,这样不会影响其他脚本
"""
namelist = []
pwdlist = []
blacklist = []
with open('./userdata.txt', 'r', encoding='utf-8') as fp:
    data = fp.readlines()
    for i in data:
        res = i.strip()
        res1 = res.split(":")
        namelist.append(res1[0])
        pwdlist.append(res1[1])
with open('./blacklist.txt', 'r', encoding='utf-8') as fp:
    data = fp.readlines()
    for i in data:
        res = i.strip()
        blacklist.append(res)


def register():
    username = input("欢迎注册,请输入用户名:")
    flag = True
    while flag:
        if username in namelist:
            username = input("用户名已存在,请更换用户名:")
        else:
            while True:
                pwd = input("请输入密码:")
                repwd = input("请输入确认密码:")
                if pwd == repwd:
                    with open('./userdata.txt', 'a+', encoding='utf-8') as fp:
                        fp.write(f"{username}:{pwd}\n")
                    print("恭喜你,注册成功!")
                    flag = False
                    break
                else:
                    print("两次输入密码不一致!请重新输入密码!")


def login():
    username = input("欢迎登录,请输入用户名:")
    isnotlogin = True
    while isnotlogin:
        pwdchange = 3
        if username in namelist:
            if username in blacklist:
                print("用户账号已锁定,请联系管理员!")
                break
            else:
                while True:
                    pwd = input(f"请输入密码,您还有{pwdchange}次机会:")
                    idx = namelist.index(username)
                    if pwd == pwdlist[idx]:
                        print("恭喜你,登录成功!")
                        isnotlogin = False
                        break
                    else:
                        pwdchange -= 1
                        if pwdchange == 0:
                            with open('./blacklist.txt', 'a+', encoding='utf-8') as fp:
                                fp.write(username+"\n")
                            print("用户账号已锁定,请联系管理员!")
                            isnotlogin = False
                            break
        else:
            username = input("用户名不存在,请重新输入用户名:")


if __name__ == '__main__':
    while True:
        num = input("请输入0--登录 and 1--注册 and q--程序结束:")
        if num == '0':
            login()
        elif num == '1':
            register()
        elif num == 'q':
            break
        else:
            num = input("输入错误!请输入0--登录 and 1--注册 and q--程序结束:")

运行结果:

E:\Programs_Way\Python\python.exe D:/Prj/_PythonSelf/Study_Basic_Grammar/_52register_and_log_in.py
请输入0--登录 and 1--注册 and q--程序结束:0
欢迎登录,请输入用户名:baba
请输入密码,您还有3次机会:111
请输入密码,您还有2次机会:123
请输入密码,您还有1次机会:999
恭喜你,登录成功!
请输入0--登录 and 1--注册 and q--程序结束:1
欢迎注册,请输入用户名:momo
请输入密码:999
请输入确认密码:999
恭喜你,注册成功!
请输入0--登录 and 1--注册 and q--程序结束:q

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值