今日主要内容:文件操作
一,文件操作基本知识
1,只读
f = open('log', mode='r', encoding='utf-8')
content = f.read()
print(content, type(content))
f.close()
# 这种方法会以bytes的方式读取,用于非文字的文件
f = open('log', mode='rb',)
content = f.read()
print(content)
f.close()
输出结果:
b’\xe9\xaa\x91\xe5\x85\xb5\xe6\xad\xa5\xe5\x85\xb5\xe4\xbd\xb3\xe7\x90\xaa\xe4\xbd\xb3\xe7\x90\xaa’
2,读写
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()
Note:对于读写操作如果先写(此时光标位置在0),会发生覆盖。
3,只写
对于只写操作,先将源文件的内容全部清除,再写。并且,没有此文件就会创建文件。
f = open('log', mode='w', encoding='utf-8')
f.write('骑兵步兵')
f.close()
f = open('log',mode='w+',encoding='utf-8')
f.write('aaa')
'''如果这个地方不调制光标,那么写完之后光标在最后的位置,什么东西也读不到'''
f.seek(0)
print(f.read())
f.close()
'''直接写进bytes的类型,需要手动将 str---> bytes'''
f = open('log',mode='wb')
f.write('附近看到类似纠纷'.encode('utf-8'))
f.close()
4,追加
f = open('log', mode='a', encoding='utf-8')
f.write('佳琪')
f.close()
进一步操作:
f = open('log',mode='a+',encoding='utf-8')
f.write('佳琪')
f.seek(0)
print(f.read())
f.close()
还可以:直接以bytes的方式追加~
f = open('log',mode='ab')
f.write('佳琪'.encode('utf-8'))
f.close()
5,实践项目
现在文本内容:我喜欢你世界
'''
注意下面字符和 字节的问题
'''
f = open('log', mode='r+', encoding='utf-8') #后面也可以写
content = f.read(3) # 读出来的都是字符
print(content)
f.seek(3) # 是按照字节定光标的位置
print(f.read())
f.tell() #告诉你光标的位置
print(f.tell())
f.close()
输出结果:
我喜欢
喜欢你世界
18
6,我们再补充一点知识
with open('log',mode='r+',encoding='utf-8') as f,open('teacher',mode='r+',encoding='utf-8') as f1:
print(f1.read())
print(f.read())
优点:不需要手动关闭文件,因为会自动关闭!
二,实践项目注册+登录
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 = i + 1
三,我们进一步补充编码的知识
#str --->byte encode 编码
s = '二哥'
b = s.encode('utf-8')
print(b)
#byte --->str decode 解码
s1 = b.decode('utf-8')
print(s1)
输出结果:
b’\xe4\xba\x8c\xe5\x93\xa5’
二哥