python自學第6天
阿新 • • 發佈:2018-04-09
IT 自學 usr div class pytho line csharp light
文件的修改:
一般是把舊文件的內容改了,在寫入到新的文件中去。
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)
python自學第6天