基本操作---文件操作

打开文件

#f = open("yesterday",'r+',encoding="utf-8") #读写
#f = open("yesterday",'w+',encoding="utf-8") #写读
#f = open("yesterday",'a+',encoding="utf-8") #追加写读
#f = open("yesterday",'wb') #写读  二进制文件
View Code

打印一行内容

f = open("yesterday",'r+',encoding="utf-8") #读写
print(f.readline())#打印一行内容
View Code

上面方法一次只能打印一行的内容,如果要打印多行内容,该怎么办呢

可以打印多行内容

f = open("yesterday",'r+',encoding="utf-8") #读写
print(f.readline())#打印一行内容
print(f.readline())
print(f.readline())
print(f.readline())
View Code

这个方法可以打印4行内容。

我要打印1000行的话,上面的方法就不现实了

使用for可以打印多行文件

f = open("yesterday",'r',encoding="utf-8")#文件句柄
count = 0
for line in f:
    if count == 4:
        print('------我是分割线------')
        count += 1
        continue
    print(line)
    count += 1
View Code

修改文件内容

f = open("yesterday",'r',encoding='utf-8')
f_new = open('new_yesterday','w',encoding='utf-8')

for line in f:
    if "夜夜笙歌" in line:
        line = line.replace("夜夜笙歌","拉啦大便")
    f_new.write(line)

f.close()
f_new.close()
View Code

 使用with也可以打开文件,并且在文件操作之后不需要再单独关闭文件

with open('new_yesterday','r',encoding='utf-8')  as f,\
      open('yesterday','r',encoding='utf-8')  as f2:
    for line in f:
        print(line)
View Code

 

你可能感兴趣的:(基本操作---文件操作)