python学习之day04

今天来总结一下文件输入输出操作的主要内容。
t文本(默认的模式):
1、读写都以str(unicode)为单位的
2、文本文件
3、必须指定encoding=‘utf-8’
没有指定encoding参数操作系统会使用自己默认的编码
linux系统默认utf-8
windows系统默认gbk
内存:utf-8格式的二进制-----解码-----》unicode
硬盘(c.txt内容:utf-8格式的二进制)
1、以t模式为基础进行内存操作
r(默认的操作模式):只读模式,当文件不存在时报错,当文件存在时文件指针跳到开始位置
with open(‘c.txt’,mode=‘rt’,encoding=‘utf-8’) as f:
print(‘第一次读’.center(50,’*’))
res=f.read() # 把所有内容从硬盘读入内存
2、w:只写模式,当文件不存在时会创建空文件,当文件存在会清空文件,指针位于开始位置
with open(‘d.txt’,mode=‘wt’,encoding=‘utf-8’) as f:
f.read() # 报错,不可读
f.write(‘擦勒\n’)
强调1:
在以w模式打开文件没有关闭的情况下,连续写入,新的内容总是跟在旧的之后
with open(‘d.txt’,mode=‘wt’,encoding=‘utf-8’) as f:
f.write(‘hello1\n’)
f.write(‘hello2\n’)
f.write(‘hello3\n’)
强调2:
如果重新以w模式打开文件,则会清空文件内容
with open(‘d.txt’,mode=‘wt’,encoding=‘utf-8’) as f:
f.write(‘hello1\n’)
with open(‘d.txt’,mode=‘wt’,encoding=‘utf-8’) as f:
f.write(‘hello2\n’)
with open(‘d.txt’,mode=‘wt’,encoding=‘utf-8’) as f:
f.write(‘hello3\n’)
3、a:只追加写,在文件不存在时会创建空文档,在文件存在时文件指针会直接调到末尾
with open(‘e.txt’,mode=‘at’,encoding=‘utf-8’) as f:
f.read() # 报错,不能读
f.write(‘hello1\n’)
f.write(‘hello2\n’)
f.write(‘hello3\n’)
强调 w 模式与 a 模式的异同:
相同点:在打开的文件不关闭的情况下,连续的写入,新写的内容总会跟在前写的内容之后
不同点:以 a 模式重新打开文件,不会清空原文件内容,会将文件指针直接移动到文件末尾,新写的内容永远写在最后
案例:a模式用来在原有的文件内存的基础之上写入新的内容,比如记录日志、注册
name=input('your name>>: ')
pwd=input(‘your name>>: ‘)
with open(‘db.txt’,mode=‘at’,encoding=‘utf-8’) as f:
f.write(’{}:{}\n’.format(name,pwd))

发布了5 篇原创文章 · 获赞 2 · 访问量 63

猜你喜欢

转载自blog.csdn.net/weixin_43138641/article/details/104844046
今日推荐