码迷,mamicode.com
首页 > 其他好文 > 详细

操作文件

时间:2018-04-13 21:24:58      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:line   odi   模式   style   读文件   操作   name   nbsp   open   

读模式   写模式  追加模式

读写模式r+  写读模式w+  追加读模式a+ 

读模式

f = open(words,r,encoding=utf-8)   #r  读模式
# print(f.read())  #读文件
# print(f.readline())   #读一行
# print(f.readlines())  #把文件的每一行放在一个list里面
f.write(hhhhh)  #写入   报错
#读模式
#1  不能写
#2  文件不存在的话会报错

写模式

f = open(words,w,encoding=utf-8)   #写模式  
f.write(hhhhh)     #打开一个存在的文件写内容,原来的内容被覆盖
f = open(names,w,encoding=utf-8)   #写模式
f.write(‘hhhhh’)    #打开一个不存在的文件,会新建一个文件,往里面写内容
print(f.read())  #读文件  报错

写模式
1 打开一个存在的文件写内容,会清空原来文件的内容
2 打开一个不存在的文件,会新建一个文件,往里面写内容
3 不能读
f = open(words,a,encoding=utf-8)
f.write(hhhhh)   #打开一个存在的文件写内容,不会清空原来的内容,在末尾添加
f = open(names,w,encoding=utf-8)  #文件不存在的话,新建一个文件
print(f.read())  #读文件  报错

追加模式

1打开一个存在的文件写内容,不会清空原来的内容,在末尾添加
2 打开一个不存在的文件,会新建一个文件,往里面写内容
3 不能读

读写模式r+

f = open(words,r+,encoding=utf-8)
f = open(word,r+,encoding=utf-8)   #文件不存在,会报错
print(f.read())  #读文件
f.write(hhhhh)  #写入

写读模式w+

f = open(words,w+,encoding=utf-8)  
f = open(word,w+,encoding=utf-8)  #可以写入
print(f.read())  #读文件,不能读
f.write(hhhhh)  #写入  文件存在,清空原来的内容,写新内容

追加读模式a+

f = open(words,a+,encoding=utf-8)
f = open(word,a+,encoding=utf-8)
print(f.read())  #读不到文件
f.write(hhhhh)  #写入

 

操作文件

标签:line   odi   模式   style   读文件   操作   name   nbsp   open   

原文地址:https://www.cnblogs.com/nuobao/p/8823854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!