标签:写入 for with open 自动 with highlight pre 用法 多个
文件的修改:
一般是把旧文件的内容改了,在写入到新的文件中去。
file_old=open("test","r",encoding="utf-8") file_new=open("test.bak","w",encoding="utf-8") for line in file_old: if "快乐等我享受" in line: line=line.replace("快乐等我享受","快乐等HunterYi享受") print(line) file_new.write(line) file_old.close() file_new.close()
with语句的用法。
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:Hunter Yi with open("test","r",encoding="utf-8") as f , open("test.bak","r",encoding="utf-8") as f2: #用with语句 可以同时打开多个文件,用完后自动关闭。 for line in f: print(line) for line2 in f2: print(line2)
标签:写入 for with open 自动 with highlight pre 用法 多个
原文地址:https://www.cnblogs.com/hunterYi/p/8757368.html