[terry笔记]文件操作

如下记录一次作业:

很显然,我这个应该属于二逼青年版,会在以后更新文艺青年版的答案。

 

1、模仿sed,一个文件中,用新字符串替换老字符串。

 1 # file = input("file_name")
 2 # old_str = input("old_str")
 3 # new_str = input("new_str")
 4 def change_str(file, old_str, new_str):
 5     f = open(file, 'r')
 6     lines = f.readlines()
 7     flen = len(lines)
 8     for i in range(flen):
 9         if old_str in lines[i]:
10             lines[i] = lines[i].replace(old_str, new_str)
11     open(file, 'w').writelines(lines)
12     f.close()
13 
14 change_str('aaa', 'A', 'ttttttttttttttttttttttttt')

 

 

2、查找、添加、删除特定的内容

 1 file=open("haproxy_conf","r")
 2 rl=file.readlines()
 3 lens=len(rl)
 4 for i in range(lens):
 5     if "oldboy.org" and "frontend" in rl[i]:
 6         if rl[i-1] is "\n":
 7             print(rl[i].strip())
 8             while True:
 9                 i += 1
10                 print(rl[i].strip())
11                 if i == lens-1:
12                     break

 

 

 

 1 arg = {
 2     'bakend': 'www.oldboy.org',
 3     'record': {
 4         'server': '100.1.7.9',
 5         'weight': 20,
 6         'maxconn': 30
 7     }
 8 }
 9 arg_list=[]
10 file=open("haproxy_conf","r+")
11 lines=file.readlines()
12 print(lines)
13 for i in arg:
14     if "bakend" == i:
15         arg_list.insert(0,i)
16         arg_list.insert(1,arg[i])
17     elif "record" == i:
18         arg_list.append(i)
19         for key,value in arg[i].items():
20             if key == "server":
21                 arg_list.insert(3,key)
22                 arg_list.insert(4,value)
23         for key, value in arg[i].items():
24             if key == "weight":
25                 arg_list.insert(5,key)
26                 arg_list.insert(6,value)
27         for key, value in arg[i].items():
28             if key == "maxconn":
29                 arg_list.insert(7,key)
30                 arg_list.insert(8,value)
31 arg_list[0]=arg_list[0]+" "+arg_list[1]+"\n"
32 arg_list.remove(arg_list[1])
33 arg_list[5]=str(arg_list[5])
34 arg_list[7]=str(arg_list[7])
35 arg_list[1]="\t"+arg_list[1]+" "+arg_list[2]+" "+arg_list[3]+" "+arg_list[4]+" "+arg_list[5]+" "+arg_list[6]+" "+arg_list[7]
36 for m in range(6):
37     n = 2
38     arg_list.remove(arg_list[n])
39 lines.append("\n")
40 lines.append("\n")
41 print(lines)
42 lines = lines +arg_list
43 print(lines)
44 file.writelines(lines)
45 file.close()

 

posted @ 2016-10-29 17:28  DoubleGinger  阅读(245)  评论(0编辑  收藏  举报