python day08 文件操作

#文件操作

1、文件路径:d:\111.txt

2、编码方式:utf-8  gbk。。。

3、操作方式:只读,只写,追加,读写,写读。。。

      以什么编码方式储存的文件,就以什么编码打开进行操作。

#只读

 只读: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
#对于w:没有此文件就会创建文件
# f = open('log',mode='w',encoding='utf-8')
# f.write('骑兵步兵')
# f.close()

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

写读 w+、w+b

# f = open('log',mode='w+',encoding='utf-8')
# f.write('aaa')
# f.seek(0)
# print(f.read())
# f.close()

#追加

追加: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()

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

#功能详解

# obj = open('log',mode='r+',encoding='utf-8')
# content = f.read(3)  # 读出来的都是字符
# f.seek(3)  # 是按照字节定光标的位置
# f.tell() 告诉你光标的位置
# print(f.tell())
# content = f.read()
# print(content)
# f.tell()
# f.readable()  # 是否刻度
# line = f.readline()  # 一行一行的读
# line = f.readlines()  # 每一行当成列表中的一个元素,添加到list中
# f.truncate(4)         #截取文件
# for line in f:
#     print(line)
# f.close()

#文件一起操作

# with open('log',mode='r+',encoding='utf-8') as f,\
#         open('log',mode='w+',encoding='utf-8') as f1:

#练习

用户注册、登录

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)

 #修改文件

with open('小护士班主任',encoding='utf-8') as f,open('小护士班主任.bak','w',encoding='utf-8') as f2:
    for line in f:
        if '星儿' in line:  #班主任:星儿
            line = line.replace('星儿','啊娇')
        #写文件
        f2.write(line) #小护士:金老板

import os
os.remove('小护士班主任') #删除文件
os.rename('小护士班主任.bak','小护士班主任')  #重命名文件

 

posted @ 2018-10-30 15:49  Null°  阅读(117)  评论(0编辑  收藏  举报