python之文件操作模式详解

以t模式为基础进行内存操作
r(默认的操作模式):只读模式,当文件不存在时报错,当文件存在时文件指针跳到最开始位置

with open ('ccc.txt',mode='rt',encoding='utf-8') as f:
	print('第一次读'.center(50,'*'))
	res = f.read() #把所有内容从硬盘读入内存
	print(res)

with open ('ccc.txt',mode='rt',encoding='utf-8') as f:
	print('第二次读'.center(50,'*'))
	res1 = f.read() #把所有内容从硬盘读入内存
	print(res1)

r模式小案例:

inp_username = input('your name:').strip
inp_password = input('your pwd:').strip
with open('user.txt',mode='rt',encoding='utf-8') as f:
	for line in f:
		username,password = line.strip().split(':')
		if inp_username == username and inp_password == password:
			print('login successful')
			break
	else:
		print('账号或密码错误')
		

w只写模式:当文件不存在时会创建空文件,当文件村子时会清空文件,指针位于开始尾椎

with open('d.txt',mode='wt',enncoding='utf-8') as f:
	#f.read() #报错,不可读
	f.write('哈哈哈哈哈哈\n')

强调1:以w模式打开文件,没有关闭的情况下,连续写入,新写的内容总是跟在内容之后

with open('d.txt',mode='wt',encoding='utf-8') as f:
	f.write('哈哈哈哈哈1\n')
	f.write('哈哈哈哈哈2\n')
	f.write('哈哈哈哈哈3\n')

强调2:如果重新以w模式打开文件,则会清空文件内容

with open('d.txt',mode='wt',encoding='utf-8') as f:
	f.write('哈哈哈哈哈1\n')
with open('d.txt',mode='wt',encoding='utf-8') as f:
	f.write('哈哈哈哈哈2\n')
with open('d.txt',mode='wt',encoding='utf-8') as f:
	f.write('哈哈哈哈哈3\n')

案例:w模式用来创建全新的文件
文件的copy工具

src_file = input('源文件路径>>:').strip()
dst_file = input('源文件路径>>:').strip()
with open (r'{
    
    }.format(src_file),mode='rt',encoding='utf-8') as f1,\
open(r'{
    
    }'.format(dst_file),mode='wt',encoding='utf-8') as f2:
	res = f1.read()
	f2.write(res)

a:只追加写,在文件不存在时会创建空文档,在文档存在时文件指针会直接调到末尾

with open('e.txt',mode='at',encoding='utf-8) as f:
	#f.read() #报错,不能读
	f.write('哈哈哈哈哈1\n')
	f.write('哈哈哈哈哈2\n')
	f.write('哈哈哈哈哈3\n')
	f.write('哈哈哈哈哈14\n')

强调:w模式与a模式的异同:
相同点:在打开的文件不关闭的情况下,连续的写,新写的内容总会跟在前写的内容之后
不同点:在以a模式重新打开文件,不会清空原文件内容,会将文件指针直接移动到文件末尾

a模式用来在原有的文件内存的基础上写入新的内容,比如记录日志、注册

name = input ('your name:')
pwd = input('your pwd:')
with open ('db.txt'.mode = 'at',encoding='utf-8') as f:
	f.write('{
    
    }:{
    
    }\n'.format(name,pwd))


#结果
lili:123
egon:123
egon:123

了解 +不能单独使用、必须配合r,w,s

with open('g.txt',mode='w+t',encoding='utf-8') as f:
     f.write('111\n')
     f.write('222\n')
     f.write('333\n')
     print('=====>',f.read())

 with open('g.txt',mode='a+t',encoding='utf-8') as f:
     f.write('444\n')
     f.write('555\n')
     print(f.read())

猜你喜欢

转载自blog.csdn.net/weixin_47237915/article/details/114552231