open(‘C:\a.txt\nb\c\d.txt’) # 注意:\ 必须转义,可以在路径前加‘r’ 或者用 /
res=f.read() print(res)
f.close() # 回收操作系统资源 f.read() # 变量f存在,但是不能再读了,报错! f.read() # 变量f存在,但是不能再读了 del f # 回收应用程序资源
# 1、在执行完子代码块后,with 会自动执行f.close() with open(‘a.txt‘,‘w‘) as f: pass # 2、可用用with同时打开多个文件,用逗号分隔开即可 with open(‘a.txt‘,‘r‘) as read_f,open(‘b.txt‘,‘w‘) as write_f: data = read_f.read() write_f.write(data)
windows下是gbk,在linux下是utf-8。
若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
with open(‘c.txt‘,mode=‘rt‘,encoding=‘utf-8‘) as f: res=f.read() # t模式会将f.read()读出的结果解码成unicode
内存:utf-8格式的二进制-----解码----->>unicode
硬盘(c.txt内容:utf-8格式的二进制)
with open(‘c.txt‘,mode=‘rt‘,encoding=‘utf-8‘) as f: res=f.read() # 把所有内容从硬盘读入内存 print(res) #实例: inp_username=input(‘your name>>: ‘).strip() inp_password=input(‘your password>>: ‘).strip() # 验证 with open(‘user.txt‘,mode=‘rt‘,encoding=‘utf-8‘) as f: for line in f: # print(line,end=‘‘) # egon:123\n username,password=line.strip().split(‘:‘) if inp_username == username and inp_password == password: print(‘login successfull‘) break else: print(‘账号或密码错误‘)
with open(‘b.txt‘,mode=‘w‘,encoding=‘utf-8‘) as f: f.write(‘你好\n‘) f.write(‘我好\n‘) f.write(‘大家好\n‘) #强调: # 1 在文件不关闭的情况下,连续的写入,后写的内容一定跟在前写内容的后面 # 2 如果重新以w模式打开文件,则会清空文件内容 #案例: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)
with open(‘c.txt‘,mode=‘a‘,encoding=‘utf-8‘) as f: f.write(‘66666\n‘) f.write(‘88888\n‘) #强调 w 模式与 a 模式的异同: # 1 相同点:在打开的文件不关闭的情况下,连续的写入,新写的内容总会跟在前写的内容之后 # 2 不同点:以 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))
r+ w+ a+ :可读可写
在平时工作中,我们只单纯使用r/w/a,要么只读,要么只写,一般不用可读可写的模式
原文:https://www.cnblogs.com/qjk95/p/12487395.html