Python modifies file content functions

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.