文件操作扩展

1.“r+”模式

r+ 写入的位置是 当前光标所在位置,会直接改写当前位置的值
r+ 可以续写么? 可以,但是必须把光标挪到最后
r 没有创建文件的能力

r_file = open("r.txt", "r+", encoding="utf-8")
r_file.write("bbb\n")
r_file.close()

r_file1 = open("r.txt", "r+", encoding="utf-8")
print(r_file1.read()) #读全文
print(r_file1.tell()) #获取当前光标所在位置
r_file1.write("aaa\n")
r_file1.close()

2.“w+”模式

w+ 拥有写入权限,可以创建文件
w 所有的write操作是先写在内存中,只有结束的时候才会执行进去
w+ 和 r+ 的区别是 r+ 只在当前位置写入,w+ 是全部重写内容

3.“w”模式追加

先读取,后写入的方式实现用w模式追加
做的所有操作都是在内存中操作,并没有落地到磁盘
解决w模式会清空替代的方式

file2 = open("w1.txt", "r", encoding="utf-8")
txt = file2.read()
print(txt)
txt = txt + "abcd\n"
txt = txt.replace("200", "200000")
#

# 以写到模式打开文件,写入内容,这个内容来自于内存
file1 = open("w1.txt", "w", encoding="utf-8")
file1.write(txt)

file2.close()
file1.close()
file = open("w1.txt","r",encoding="utf-8")
txt = file.read()
print(txt)

file1 = open("w2.txt","w",encoding="utf-8")
file1.write(txt)

file.close()
file1.close()

3.下列数据是用户信息表,基于性别,把男性写入到nan.txt,女性写入到nv.txt

1   xiaowang    男
2 xiaohei 女
3 xiaohong 男
4 xiaobai 男
5 xiaozi 女
方法一:
file = open("w.txt","r",encoding="utf-8")
file1 = open("nan.txt", "a+", encoding="utf-8")
file2 = open("nv.txt", "a+", encoding="utf-8")

for line in file:
line = line.strip()
print("line::", line)
if line.find("男") != -1:
file1.write(line+"\n")
if line.find("女") != -1:
file2.write(line+"\n")

file.close()
file1.close()
file2.close()

方法二:(需要手动创建文件nan.txt、nv.txt, “r+”模式没有创建文件的能力)

file = open("w.txt","r",encoding="utf-8")
file1 = open("nan.txt", "r+", encoding="utf-8")
file2 = open("nv.txt", "r+", encoding="utf-8")

for line in file:
line = line.strip()
if line.count("男") > 0:
file1.read()
file1.write(line+"\n")
if line.count("女") > 0:
file2.read()
file2.write(line+"\n")

file.close()
file1.close()
file2.close()

 

posted @ 2021-01-07 23:42  chenghuahua  阅读(64)  评论(0编辑  收藏  举报