# 一行一行的读# 默认是添加了换行,可以在后面加上.strip()
content = rf.readline().strip()# 读下一行/读一行
content = rf.readline()# 读取所有行,结果是列表
content = rf.readlines()# 注意加了s, readlines()# 可用于遍历# for line in rf.readlines()print(line)# 这里循环的的是列表print(content)
# 最佳读取方式# 循环读取这种方式是最好的,每次读取一行内容,不会产生内存溢出的问题
f =open("../def/哇擦.txt", mode="r", encoding="utf-8")for line in f:print(line.strip())# 这里循环的是文件句柄# for 可以一行一行的处理数据
# 优化:
file_name =input("please enter you need copy file name:")
index_dot = file_name.rfind(".")
copy_name = file_name[:index_dot]+"_副本"+ file_name[index_dot:]withopen(copy_name, mode="w", encoding="utf-8")as copy_file, \
open(file_name, mode="r", encoding="utf-8")as source_file:for line in source_file:
copy_file.write(line)
copy_file.flush()
文件修改
# 引入模块import os
import time
# 打开目标文件# f1 = open("你昨天干嘛去了", mode="r", encoding="utf-8")withopen("你昨天又干嘛去了", mode="r", encoding="utf-8")as f1, \
open("你昨天又干嘛去了_副本", mode="w", encoding="utf-8")as f2:# 在同一行还要换行进行相同的操作,可以写,\for line in f1:
line = line.replace("你","sb")#此处进行修改操作
f2.write(line)
time.sleep(3)# 删除文件
os.remove("你昨天又干嘛去了")
time.sleep(3)# 重命名文件
os.rename("你昨天又干嘛去了_副本","你昨天又干嘛去了")
# 拓展:修改方式为,在某一行添加一行新内容import os
withopen("练习修改.txt",mode="r",encoding="utf-8")as rf1 ,\
open("练习修改_副本.txt",mode="w",encoding="utf-8")as rf2:for line in rf1:if line.strip()=="that begin!":
rf2.write("这是在前面增加的内容\n")
rf2.write(line)
os.remove("练习修改.txt")
os.rename("练习修改_副本.txt","练习修改.txt")
>>>实战:读取一个日志文件,将它每行以字典的方式保存,并都放入一个列表中
'''
.log文件
id,name,phone,car,home,salary
1,alex,10086,特斯拉,于辛庄,5000000
2,wusir,10010,五菱宏光,青年,400000
3,taibai,10000,魔板单车,松兰堡,30000
4,ritian,12345,小黄车,广东,30000
'''
li =[]withopen("2019-6-11.log", mode="r", encoding="utf-8")as rf:
first = rf.readline().strip().split(",")# type(first)list 把行首的内容读取到for line in rf:
dic ={}
content = line.strip().split(",")for i inrange(len(first)):
dic[first[i]]= content[i]
li.append(dic)print(li)# 解构,元素少的时候'''
infor.txt
1,alex,10086
2,wusir,10010
3,taibai,10000
4,ritian,12345
'''
lis =[]withopen("infor.txt", mode="r", encoding="utf-8")as rf:for line in rf:
dic ={}
a, b, c = line.strip().split(",")
dic ={"num": a,"name": b,"phone": c}
lis.append(dic)
>>>实战:对文件内容进行计算
'''
.txt 文件
name:apple price:10 amount:3 year:2012
name:tesla price:100000 amount:1 year:2013
'''
rf =open("eat.txt", mode="r", encoding="utf-8")
res =[]for line in rf:
content = line.strip().split()
dic ={}for re in content:
key, value = re.strip().split(":")
dic[key]= value
res.append(dic)print(res)# [{'name': 'apple', 'price': '10', 'amount': '3', 'year': '2012'},# {'name': 'tesla', 'price': '100000', 'amount': '1', 'year': '2013'}]sum=0for li in res:sum=sum+int(li["price"])*int(li["amount"])print(sum)
# 实战:模拟用户注册和登录
user_name =input("please enter your register user name:")
user_code =input("please enter your register code:")withopen("login.txt","w", encoding="utf-8")as wf:
wf.write("{}\n{}".format(user_name, user_code))# 巧用format写入多个参数print("Congratulations you register succeed!")
i =0
li =[]while i <3:
usn =input("please enter your user name:")
pwd =input("plese enter your code:")withopen("login.txt","r+", encoding="utf-8")as rf:for line in rf:
li.append(line.strip())if usn == li[0].strip()and li[1].strip()== pwd:print("login succeed!")breakelse:print("your enter username or usercode is worng!")if i ==2:print("your count is frozen!")
i +=1