Skip to content

Instantly share code, notes, and snippets.

@neoatlantis
Created July 12, 2019 12:26
Show Gist options
  • Save neoatlantis/1ee1ea25928076ee65aae5abd620d172 to your computer and use it in GitHub Desktop.
Save neoatlantis/1ee1ea25928076ee65aae5abd620d172 to your computer and use it in GitHub Desktop.
按照自定义的要求修改一个文本文件。给朋友的例子。
#!/usr/bin/env python3
def modify_line(original, lineid):
"""在本函数下面定义要进行的修改。
如果不需要作出修改,应当直接退出函数。如果需要作出修改,让函数返回一个
字符串。使用 lineid 得知需要处理哪一行,lineid 不将空行计算在内。
范例:
修改第一行,在第三个字符后面加上逗号。
修改第二行,在结尾加上 # test 的字样。
"""
if lineid == 1:
# 截取前三个字符,加上逗号,再和原来的第三个字符之后的部分拼接
return original[0:3] + "," + original[3:]
if lineid == 2:
return original + " # test"
##############################################################################
import os
import sys
if len(sys.argv) < 2:
print("用法:\n python3 modify-file-by-line.py 输入文件名 > 输出文件名")
exit()
with open(sys.argv[1], "r") as inputfile:
lineid = 0
for line in inputfile:
if not line.strip():
print("") # 输入了一个空行,因此保持输出中也有一个空行
continue # 然后不作处理,直接跳到下一行
oldline = line.rstrip() # 去掉这一行后面的回车
lineid += 1 # 非空行,行号计数+1
newline = modify_line( # 调用修改函数,过滤这一行,看看是否需要处理
oldline,
lineid=lineid
)
if type(newline) == str: # 如果修改函数返回了结果,就修改
print(newline)
else: # 否则输出原有的行
print(oldline)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment