展开全部
from random import random
import os
class Filehandle(object):
def __init__(self):
pass
def handle_file(self, file_path):
# To get the content of the txt file
file_content = open(file_path, "r")
# create a list container to save the new content
f_list = []
# handle the old content to produce the new content
# you can change the handle code on your own
for i in file_content:
i_name = i.split("[")[0]
i_value_new = str(random()) + " " + str(random())
i_new = i_name + "[" + i_value_new + "]"
f_list.append(i_new)
# close the file
file_content.close()
# open the file to wride mode
f_w = open(file_path, "w")
# file the file with the new content
for i in f_list:
f_w.write(i + os.linesep)
# close the file
f_w.close()
if __name__ == "__main__":
path = "/Users/mymachine/myProject/file.txt"
fh = Filehandle()
fh.handle_file(path)
# go to check the txt file which is already changed to new content.