python3的自学之路--8_python的文件操作

1.文件操作

           文件的编码方式:utf-8,gbk....以什么编码方式存储的文件,就以什么编码打开进行操作,否则出现乱码。

           操作方式:只读,只写,追加,读写,写读.....

 

只读:r,rb

        f = open('模特主妇护士班主任',mode='r',encoding='utf-8')
        content = f.read()
        print(content,type(content))
        f.close()

        # f = open('模特主妇护士班主任',mode='rb',)
        # content = f.read()
        # print(content)
        # f.close()

r+读写

r+b读写(以bytes类型)

        # f = open('log',mode='r+',encoding='utf-8')
        # print(f.read())
        # f.write('大猛,小孟')
        # f.close()

        f = open('log',mode='r+b')
        print(f.read())
        f.write('大猛,小孟'.encode('utf-8'))
        f.close()

 

只写:w,wb

    # 先将源文件的内容全部清除,在写。
    # f = open('log',mode='w',encoding='utf-8')
    # f.write('附近看到类似纠纷')
    # f.close()

    f = open('log',mode='wb')
    f.write('附近看到类似纠纷'.encode('utf-8'))
    f.close()
    w+
    # f = open('log',mode='w+',encoding='utf-8')
    # f.write('aaa')
    # f.seek(0)
    # print(f.read())
    # f.close()
    w+b
    .......

追加 a,ab

        # f = open('log',mode='a',encoding='utf-8')
        # f.write('佳琪')
        # f.close()

        # f = open('log',mode='ab')
        # f.write('佳琪'.encode('utf-8'))
        # f.close()

文件操作之注册,登陆

username = input('请输入你要注册的用户名:')
password = input('请输入你要注册的密码:')
with open('list_of_info',mode='w',encoding='utf-8') as f:
    f.write('{}\n{}'.format(username,password))
print('恭喜您,注册成功')
lis = []
i = 0
while i < 3:
    usn = input('请输入你的用户名:')
    pwd = input('请输入你的密码:')
    with open('list_of_info',mode='r+',encoding='utf-8') as f1:
        for line in f1:
            lis.append(line)
    if usn == lis[0].strip() and pwd == lis[1].strip():
        print('登录成功')
        break
    else:print('账号和密码错误')
    i+=1

编码,解码。

#str --->byte  encode 编码
# s = '二哥'
# b = s.encode('utf-8')
# print(b)
# #byte --->str decode 解码
# s1 = b.decode('utf-8')
# print(s1)


# s = 'abf'
# b = s.encode('utf-8')
# print(b)
# #byte --->str decode 解码
# s1 = b.decode('gbk')
# print(s1)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值