展开全部
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.
博客展示了用Python处理txt文件的代码。定义了Filehandle类,其handle_file方法读取txt文件内容,对每行内容进行处理生成新内容,存储在列表中,最后以写入模式打开文件,将新内容写入并覆盖原内容。

564

被折叠的 条评论
为什么被折叠?



