#1、文件操作之追加数据01:
f = open("yesterday01",'a+U',encoding="utf-8")
#a= append,追加之意,w则为写入并覆盖,r为只读,+表示可同时读写,
# U表示在读取时,可以将
自动转换为
,如 r+U,b表示处理的是二进制文件(如ftp需用rb,wb)
f.write("
when i was young I like to listen to the radio
")
data = f.read()
print(data)
f.close()
#2、文件操作之读前3行的数据:
f = open("yesterday01","r",encoding="utf-8")
for i in range(3):
print(f.readline())
#3、打印所有的行:
f = open("yesterday01","r",encoding="utf-8")
for line in f.readlines():
print(line)
#4、以下的作用待查:
f = open("yesterday01","r",encoding="utf-8")
for line in f.readlines():
#print(f.readline())
print(f.tell())
f.seek(2)
print(f.readline())
#5、打印出修改的内容并写入备份的文档中:
f = open("yesterday01","r+",encoding="utf-8")
f_bak = open("yesterday01bak","a+",encoding="utf-8")
for line in f.readlines(): #注意是带s的,()表示所有
if "raddio" in line:
line = line.replace("raddio","MP3")
f_bak.write(line)
print (line)
f.close()
f_bak.close()
#6、回车键:
f = open("yesterday01","a+",encoding="utf-8")
f.write("---hello------
")
f.write("---hello------
")
f.write("---hello------
")
#7、??:
import sys
f = open("yesterday01","r+",encoding="utf-8")
f_bak = open("yesterday01bak","a+",encoding="utf-8")
find_str = sys.argv[1]
replace_str = sys.argv[2]
for line in f.readlines():
if find_str in line:
line = line.replace(find_str,replace_str)
f_bak.write(line)
print (line)
f.close()
f_bak.close()
#8、不需要用close关闭文件的方法(读最前面的42个字符,不足一行则显示一行的内容):
with open("yesterday01","r+",encoding="utf-8") as f:
for line in f.readlines(42):
print (line)