替换oldtxt,newtxt
for line in fileinput.input("filepath",inplace=1):
line=line.replace("oldtxt",“newtxt”)
print line
例子2(
f1 = file("hello.txt", "r") f2 = file("myhello.txt", "w") for s in f1.readlines(): f2.writes(s.replace("hello","hi")) #调用replace函数将s中的“hello”替换为“hi”, f1.close() f2.close()
)
修改某行:
with open("fo.txt","r+") as f:
old=f.read()
f.seek(0)
f.write("new line\n" + old)
line before