第8次预习课-0817
第8次预习课笔记 20180815
所有的变量、数据和计算过程放在内存里面完成的。
fp=open("D:\\up\\a.txt","r",encoding="utf-8")
data = fp.read()
fp.close()
print(data)
fp.read() 读到一个字符串里面
fp.readline() 读取一行
fp.readlines() 读取多行放在列表中
题目:找出文件中所有包含test的行号
1 fp = open("D:\\up\\a.txt","r",encoding="utf-8") 2 data = fp.readlines() 3 print(data) 4 fp.close() 5 6 lines =[] 7 8 for i in range(len(data)): 9 if "test" in data[i]: 10 lines.append(i+1) 11 print(lines)
文件读取的时候,行的末尾包含回车符号的

Strip 回车换行空格tab,等都会去掉
XXX.strip()
Read() 、Readlines()
Readline()
如果文件很大,你用read会导致内存不够; 用readline来读超大文件,一行一行读。
内存在电脑中是个稀缺的资源,如果你大量占用,程序肯定不是最优的
小文件,直接用read读速度会稍微快一些
r: read w: write a: append rb: read binary wb: write binary ab: append binary
r+ : read and write
w+ :write and read
a+ :append and read
只设置了读的模式,但是写了写的方法,会报错

w 是清空写,将原有的清空 (慎用)
w+ 先清空内容再写入,然后才可以读取你写入的内容 (慎用)
r+ 不清空内容,可以同时读和写入内容
a+ 追加写,所有写的内容都在文件的最后

题目:在指定目录下新建10个test文件,类似 1.txt。。。
for i in range(1,11):
fp=open("d:\\up\\"+str(i)+".txt","w",encoding="utf-8")
fp.close()
文件不关闭时,写入的内容,如果太少,实际写的内容,并不会立即写到磁盘上
如果没有写close(),直接python进行关闭了,操作系统也会自动把内容写入
不关闭,会将句柄耗尽
#这种会自动关闭 with = open +close
with open("d:\\up\\a.txt","r",encoding="utf-8") as fp:
print(fp.read())
题目:写一个文件,里面写入从gloryroad1~ gloryroad100,写入之后再读出来
1 with open("d:\\up\\b.txt","w",encoding="utf-8") as fp: 2 for i in range(1,101): 3 fp.write("gloryroad"+str(i)+"\n") 4 5 with open("d:\\up\\b.txt","r",encoding="utf-8") as fp: 6 data = fp.read() 7 8 print(data)
如果读取文件不存在的话

a 文件写在最后的部分
r+ 从开始写,并将已有的覆盖
文件游标的位置:
r+ 文件打开的时候,r或者w都是默认文件0这个位置
fp.tell() 文件在什么位置
fp.seek(0,0) 回到开始
offset:相对的坐标 正数:从前向后 负数:从后向前 0表示最开始的游标
whence:
(1和2 的使用基于rb模式)
0 , 表示从文件最开始位置;
1, 表示从当前位置开始,基本当前的相对位置,来重置坐标;
10 seek(5,1) 10à5
2, 2 表示从文件的末尾开始,做相对位置,来重置坐标
Seek(-5,2) 文件末尾向前数5
作业:
构造一个文件,将所有alex字符,替换成superman
1 with open("d:\\up\\a.txt","r",encoding="utf-8") as fp1: 2 with open("d:\\up\\b.txt","w",encoding="utf-8") as fp2: 3 data = fp1.readlines() 4 for i in data: 5 if "alex" in i: 6 i = i.replace("alex","superman") 7 fp2.write(i) 8 9 with open("d:\\up\\b.txt","r",encoding="utf-8") as fp2: 10 print(fp2.read())

浙公网安备 33010602011771号