Python小程序之sed命令替换

python

需求:

  编写sed命令脚本

代码如下

 1 # Author:Lee Sir

2

3 import sys,os

4

5 des_file = r'E:\StartPython\day3\test.txt'

6 des_file1 = r'E:\StartPython\day3\test1.txt'

7

8 parameter = ['0','Somehow','123',des_file]

9

10 def usage(parameter):

11 if len(parameter) == 4:

12 if isinstance(parameter[1],str) and isinstance(parameter[2],str):

13 old_str = parameter[1]

14 new_str = parameter[2]

15 if os.path.exists(parameter[3]):

16 des_file = parameter[3]

17 return True, old_str, new_str, des_file

18 return False

19

20 def check_string_exist(old,file):

21 with open(file,encoding='utf-8') as fd:

22 for line in fd:

23 if old not in line:

24 return False

25 else:

26 return True

27

28 def replace(old,new,file):

29 with open(file,'r+',encoding='utf-8') as fd,open(des_file1,'w+',encoding='utf-8') as fd1:

30 for line in fd:

31 if old in line:

32 new_line = line.replace(old,new)

33 else:

34 new_line = line

35 print(new_line)

36 fd1.write(new_line)

37

38 def main():

39 result = usage(parameter)

40 if result:

41 if check_string_exist(result[1],result[3]):

42 replace(result[1],result[2],result[3])

43 else:

44 print('the %s is not found in %s ' % (result[1],result[3]))

45 else:

46 exit('USAGE: %s old_str new_str des_file' % sys.argv[0])

47

48 if __name__ == '__main__':

49 main()

以上是 Python小程序之sed命令替换 的全部内容, 来源链接: utcz.com/z/388421.html

回到顶部