Since Python does not have a way to modify the contents of a file, it has written two functions to modify the contents of the file.
ImportOSdefChange_file (address,line,content):#Modify a file to specify a lineF=open (Address,"R", encoding="Utf-8") F2=open ("Temporary_file.txt","W", encoding="Utf-8") I=0 forVinchf:i+=1ifi==line:f2.write (content)Else: F2.write (v) f.close () F2.close () F= Open (Address,"W", encoding="Utf-8") F2=open ("Temporary_file.txt","R", encoding="Utf-8") forVinchF2:f.write (v) f.close () F2.close () change_file ("Yesterday.txt", 1,"OLS li\n")defFile_replace (address,find_str,replace_str,replacenum=1): #Replace the file with the specified word, replaced by default once,With open (address,"R", encoding="Utf-8") as F, open ("Temporary_file.txt","W", encoding="Utf-8") as F2:ifReplacenum <=0:return0Else: forVinchF:ifReplacenum = =0:f2.write (v)Else: ifReplacenum <=V.count (FIND_STR): F2.write (V.replace (Find_str, Replace_str, Replacenum)) Replacenum=0Else: F2.write (V.replace (Find_str, replace_str)) Replacenum= Replacenum-V.count (find_str) F= Open (Address,"W", encoding="Utf-8") F2=open ("Temporary_file.txt","R", encoding="Utf-8") forVinchF2:f.write (v) f.close () F2.close () file_replace ("Yesterday.txt","Yesterday","Today", 2)
Python modifies file content functions