# Auther:aaron Fan
‘‘‘
Ideas:
The purpose is to modify yesterday this file, but because it is not possible to directly modify the file, so the modified content needs to be written to the high yesterday.new this file,
And then overwrite the contents of the yesterday.new into the yesterday file.
f = open (' Yesterday ', ' R ', encoding= ' utf-8 ')
f_new = open (' Yesterday.new ', ' W ', encoding= ' utf-8 ')
For line in F:
If "wanton pleasures, etc I enjoy" in line:
line = Line.replace ("Wanton happiness and so on I enjoy", "wanton happiness waiting for Aaron to enjoy")
F_new.write (line)
F.close ()
F_new.close ()
#改进版 (achieve sed-like functionality):
Import Sys
f = open (' Yesterday ', ' R ', encoding= ' utf-8 ')
f_new = open (' Yesterday.new ', ' W ', encoding= ' utf-8 ')
#命令行参数, the string that needs to be changed
FIND_STR = sys.argv[1]
#命令行参数, which string to change to
REPLACE_STR = sys.argv[2]
For line in F:
If FIND_STR in line:
line = Line.replace (FIND_STR,REPLACE_STR)
F_new.write (line)
F.close ()
F_new.close ()
#需要在命令行下去测试 (the source file yesterday needs to exist), use the following command:
The modification of the #python file files implements a function similar to sed. py "Wanton happiness and so I enjoy" "Wanton joy waiting for Aaron to enjoy"
‘‘‘
The #使用with语句的改进版 (with) is to automatically close the file when the WITH statement finishes executing, so the file operation should use with):
Import Sys
With open (' Yesterday ', ' R ', encoding= ' utf-8 ') as F, \
Open (' Yesterday.new ', ' W ', encoding= ' Utf-8 ') as F_new:
#命令行参数, the string that needs to be changed
FIND_STR = sys.argv[1]
#命令行参数, which string to change to
REPLACE_STR = sys.argv[2]
For line in F:
If FIND_STR in line:
line = Line.replace (FIND_STR,REPLACE_STR)
F_new.write (line)
#需要在命令行下去测试 (the source file yesterday needs to exist), use the following command:
The modification of the #python file files implements a function similar to sed. py "Wanton happiness and so I enjoy" "Wanton joy waiting for Aaron to enjoy"
Python3-file's modification implements functions like sed in the shell