Python 读写txt文件操作

一、“r” ,"w" ,”a“ 三种模式

 一般地,为了避免文件的浪费,使用with open("fileName") as f

f = open("fileName",'r',encoding="UTF-8")  #读模式
f = open("fileName",'w',encoding="UTF-8")  #写模式创建一个新的文件,会覆盖以前的文件
f = open("fileName",'a',encoding="UTF-8")  #追加模式写入到文件,不会覆盖以前的文件

f = open("fileName",'r+',encoding="UTF-8")  #读写,先读再写入

f = open("fileName",'w+',encoding="UTF-8")  #写读,先创建一个文件,然后再读

f = open("fileName",'a+',encoding="UTF-8")  #追加读

f = open("fileName",'rb',encoding="UTF-8")  #以二进制文件读

f = open("fileName",'wb',encoding="UTF-8")  #以二进制文件写

二、文件操作
f.read() #读所有文件
f.readlines() #读一行文件
三、循环
for index,line in enumerate(f.readlines()): #可以得到索引下标
  print(line.strip().slipt()) #line.strip() 去除换行; .slipt() 除去空格
四、进度条
import sys,time
for i in range(20):
sys.stdout.write("#") #写入
sys.stdout.flush() #刷新
time.sleep(0.1)
五、文件修改
f = open("fileName","r",encoding="UTF-8")  #从这个文件中读
new_f = open("new_shoppingCar.txt","w",encoding="UTF-8") #写入这个文件中
for line in f:
if "书桌" in line:
line = line.replace("书桌","学生书桌") #使用第二个字符串替换第一个字符串
new_f.write(line)
f.close()
new_f.close()



 

posted @ 2019-03-07 10:14  xiao幸运  阅读(1088)  评论(0编辑  收藏  举报