python基础day10 文件相关操作

文件的基本操作

三步骤:

1. 打开文件

关键字:open

f = open(r'a.txt', 'r', encoding = 'utf8')
f = open(r'a.txt', made = 'r',encoding = 'utf8')
print(f)  # 操作系统打开的文件

2. 操作文件

读、写

res = f.rean()
print(res)

3. 关闭文件

释放资源的

f.close()

# 方式2
# with上下文管理器
with open('a.txt','r', encoding = 'utf8') as f:
    print(f.read())

文件的读写模式

r:read(读)

w:write(写)

a:append(追加写)

# 读模式
# 1. 路径不存在,直接报错
with open('a.txt', 'r', encoding = 'utf8') as f:
    pass

# 2.路径存在
with open('a.txt', 'r', encoding = 'utf8') as f:
    print(f.read())

# 写模式
# 1. 路径不存在的,会自动创建出来文件
with open('a.txt','w', encoding = 'utf8') as f:
    pass

'''我们真正的代码以后是要运行在Linux系统里面去的,服务器:一台计算机,Linux系统(centos、Redhat等),去阿里云或者腾讯云上去买.'''
# 2. 路径存在
# 把文件内的原本数据情况掉,从新写入,覆盖!!!
# w模式很危险,
with open('a.txt', 'w', encoding='utf8') as f:
    f.write('hello big baby!')
    f.write(str(123))  # 写文件的数据类型必须是字符串类型,和字节类型,其他类型都不能直接写入,

# 3. 追加模式
# 3.1 路径不存在,会自动创建文件出来
with open('a.txt', 'a', encoding='utf8') as f1:
    f1.write('hello baby!')
    pass

# 路径存在,在文件的原来数据后面继续追加新的内容
with open('a.txt', 'a', encoding='utf8') as f1:
    f1.write('hello baby!\n')

 

文件的操作方法

1. 读系列

# 1. 读系列
with open('a.txt', 'r', encoding='utf8') as  f:
    print(f.read())
    # 一次读取文件的一行内容,一行一行读取
    print(f.readline()) # hello worldhello baby!hello baby!
    print(f.readlines())  # ['hello world\n', 'hello baby!\n', 'hello baby!\n', 'hello baby!\n']
    # 判断文件是否可读
    print(f.readable()) # True

2. 写系列
# 2. 写系列
with open('a.txt', 'w', encoding='utf8') as f:
    f.write('hello baby')
    f.write(str(123)) # 只能写字符串
    print(f.writable()) # True
    print(f.readable()) # False
    f.writelines(['hello\n', 'world\n', 'kevin', 'jack'])

文件的读操作优化

with open('a.txt', 'r', encoding='utf8') as f:
    '''
        read方法它是一次性读取文件的所有内容,所以,当文件内容非常大的时候,有可能会造成内存溢出
        我们不允许内存溢出的情况出现,但是当文件内容非常小的时候,无所谓了,
        
        针对上述出现的问题,如何解决呢?
    '''
    print(f.read()) # 一次性把文件中的内容读取完毕
    print(f.read())
    print(f.read())
    print(f.read())
    # 变量f它值支持for循环的
    for line in f:
        print(line)  # for循环就是一行一行的读取内容的
        '''所以,以后读文件的时候,如果觉得文件很大,我们就是要for循环一行一行的读取'''

课堂练习

1. 简易版本的注册与登录功能:用户的数据要保存在文件里面
    # 只注册一次
    '''把用户的用户名和密码给保存起来,登录就是使用用户注册时候保存的用户名和密码进行比较'''
# 1. 注册功能:数据需要保存在文件里

# 1.1 让用户输入用户名和密码
username = input('请输入你的用户名>>>:').strip()
password = input('请输入你的密码>>>:').strip()

# 2. 把用户名和密码保存到文件里
res = '%s|%s' % (username, password)
# format
with open('userinfo.txt', 'w', encoding='utf8') as f:
    f.write(res)
    print('%s:注册成功' % username)
    
2. 简易版本的登录功能
# 2. 简易版本的登录功能
# 2.1 让用户输入用户名和密码
username = input('请输入你的用户名:').strip()
password = input('请输入你的密码:').strip()

# 3. 先读取文件,然后从文件中获取真实的用户名和密码
with open('userinfo.txt', 'r', encoding='utf8') as f:
    data = f.read()  # tank|123

# 4. 处理字符串,处理成列表的形式,切分
res = data.split('|')  # res: ['tank', '123']
# real_username, real_password = data.split('|')  # res: ['tank', '123']

# 5. 比较用户名和密码是否正确
if username == res[0] and password == res[1]:
    print('登录成功')
else:
    print('用户名或者密码错误')

 

多用户注册和多用户下的登录功能

# 多用户注册功能:
while True:
    username = input('请输入你的用户名>>>:').strip()
    password = input('请输入你的密码>>>:').strip()

    # 3. 验证用户名是否已经存在
    with open('userinfo.txt', 'r', encoding='utf8') as f1:
        for line in f1:
            # line: kevin|123
            if username == line.split('|')[0]:
                print('用户名已经存在')
                break
        else:
            # 2. 把用户名和密码保存到文件里
            res = '%s|%s\n' % (username, password)

            # format
            with open('userinfo.txt', 'a', encoding='utf8') as f:
                f.write(res)
                print('%s:注册成功' % username)

 # 2. 多用户下的登录功能
# 多用户下的登录功能
# 1. 让用户输入用户名和密码
username = input('请输入你的用户名:').strip()
password = input('请输入你的密码:').strip()

# 2. 从文件里读取用户名和密码
with open('userinfo.txt', 'r', encoding='utf8') as f:
    for line in f:
        # line: jason|123
        data=line.split('|')  # ['kevin', '123\n']
        # real_username, real_password = line.split('|')  # ['kevin', '123\n']
        # real_password.strip('\n')
        # 判断用户名和密码
        if username == data[0] and password == data[1].strip('\n'):
            print('登陆成功')
            break
        else:
            print('用户名和密码错误')

代码整合

#### 代码整合:
while True:
    print("""
        1. 注册功能
        2. 登录功能
    """)

    choice = input('请输入你要执行的序号:').strip()
    if not choice.isdigit():
        print('请好好输入,我们没有这个功能')
        continue
    # 验证序号在1、2范围之内
    if choice == '1':
        # 注册功能
        while True:
            username = input('请输入你的用户名>>>:').strip()
            password = input('请输入你的密码>>>:').strip()

            # 3. 验证用户名是否已经存在
            with open('userinfo.txt', 'r', encoding='utf8') as f1:
                for line in f1:
                    # line: kevin|123
                    if username == line.split('|')[0]:
                        print('用户名已经存在')
                        break
                else:
                    # 2. 把用户名和密码保存到文件里
                    res = '%s|%s\n' % (username, password)

                    # format
                    with open('userinfo.txt', 'a', encoding='utf8') as f:
                        f.write(res)
                        print('%s:注册成功' % username)
    elif choice == '2':
        # 登录功能
        username = input('请输入你的用户名:').strip()
        password = input('请输入你的密码:').strip()

        # 2. 从文件里读取用户名和密码
        with open('userinfo.txt', 'r', encoding='utf8') as f:
            for line in f:
                # line: jason|123
                data=line.split('|')  # ['kevin', '123\n']
                # real_username, real_password = line.split('|')  # ['kevin', '123\n']
                # real_password.strip('\n')
                # 判断用户名和密码
                if username == data[0] and password == data[1].strip('\n'):
                    print('登陆成功')
                    break
                else:
                    print('用户名和密码错误')

文件的操作模式

t 模式:text文本

r  >>>  rt

w  >>>  wt

a  >>>  at

1. 它是以字符串位基本单位
2. 它只能操作字符串形式
3. encoding参数必须写

 

b模式:bytes二进制模式

r  >>>  rb

w  >>>  wb

a  >>>  ab

1. b不能省略,必须写 rb
2. 它可以操作任意的数据类型:视频、音频、图片等都可以
3. encoding参数必须不能写
4. 它的数据以字节为单位了

 

posted @ 2023-05-24 15:16  吼尼尼痛  阅读(25)  评论(0)    收藏  举报