Two methods for getting started with python to modify file content

1. Account for hard disk modification

import ox

file_name="兼职.txt"

new_file_name="%s.new".% file_name

old_str="hong" #The amount to be replaced

new_str="hong"#The amount that needs to be replaced

old_f=open(file_name,"read")

new_f=open(new_file_name,"w")

for line in file_name:

      if old_str in line:

            line=line.replace(old_str,new_str)

      new_f.write(line)

old_f.close()

new_f.close()

ox.replace(new_f,old_f) #The new folder overwrites the old folder

 

2. Occupy memory modification

old_str = "hong"

new_str = "洪"

file_name = "兼职.txt"

f=open(file_name,"r+")

data=f.read()

a = data.replace(old_str,new_str)

f.truncate(0)

f.write(a)

f.close()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325980384&siteId=291194637