Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. def modify_line(original, lineid):
  4. """在本函数下面定义要进行的修改。
  5.  
  6. 如果不需要作出修改,应当直接退出函数。如果需要作出修改,让函数返回一个
  7. 字符串。使用 lineid 得知需要处理哪一行,lineid 不将空行计算在内。
  8.  
  9. 范例:
  10. 修改第一行,在第三个字符后面加上逗号。
  11. 修改第二行,在结尾加上 # test 的字样。
  12. """
  13.  
  14. if lineid == 1:
  15. # 截取前三个字符,加上逗号,再和原来的第三个字符之后的部分拼接
  16. return original[0:3] + "," + original[3:]
  17.  
  18. if lineid == 2:
  19. return original + " # test"
  20.  
  21.  
  22.  
  23.  
  24. ##############################################################################
  25.  
  26. import os
  27. import sys
  28.  
  29. if len(sys.argv) < 2:
  30. print("用法:\n python3 modify-file-by-line.py 输入文件名 > 输出文件名")
  31. exit()
  32.  
  33. with open(sys.argv[1], "r") as inputfile:
  34. lineid = 0
  35. for line in inputfile:
  36. if not line.strip():
  37. print("") # 输入了一个空行,因此保持输出中也有一个空行
  38. continue # 然后不作处理,直接跳到下一行
  39.  
  40. oldline = line.rstrip() # 去掉这一行后面的回车
  41. lineid += 1 # 非空行,行号计数+1
  42.  
  43. newline = modify_line( # 调用修改函数,过滤这一行,看看是否需要处理
  44. oldline,
  45. lineid=lineid
  46. )
  47.  
  48. if type(newline) == str: # 如果修改函数返回了结果,就修改
  49. print(newline)
  50. else: # 否则输出原有的行
  51. print(oldline)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement