Python利用fileinput实现文件特定行插入与替换
本文详解Python中利用fileinput模块实现文件特定行插入与替换的方法。通过设置inplace=1重定向输出,可模拟类似sed的功能,在指定行号插入内容或匹配模式进行替换,适用于小型文本处理场景。
Python文件特定行插入和替换实例详解
Python标准库提供了read和write方法,但与其他许多编程语言类似,似乎并未直接提供insert方法。虽然理论上可以实现insert功能,但若在插入过程中发生崩溃,可能导致后续内容未能及时写回,从而引发数据一致性问题。
不过,借助fileinput模块可以较为简单地实现向特定行插入内容的需求:
Python代码
import os
import fileinput
def file_insert(fname,linenos=[],strings=[]):
"""
Insert several strings to lines with linenos repectively.
The elements in linenos must be in increasing order and len(strings)
must be equal to or less than len(linenos).
The extra lines ( if len(linenos)> len(strings)) will be inserted
with blank line.
"""
if os.path.exists(fname):
lineno = 0
i = 0
for line in fileinput.input(fname,inplace=1):
# inplace must be set to 1
# it will redirect stdout to the input file
lineno += 1
line = line.strip()
if i<len(linenos) and linenos[i]==lineno:
if i>=len(strings):
print "\n",line
else:
print strings[i]
print line
i += 1
else:
print line
file_insert('a.txt',[1,4,5],['insert1','insert4'])
需要注意的是,fileinput.input函数的inplace参数必须设置为1,这样可以将stdout重定向到输入文件中,从而实现原地修改文件的效果。
当然,使用fileinput.input不仅限于在特定行插入内容,还可以针对符合特定模式的行(例如以salary:结尾的行)进行插入或替换,从而实现一个小型的sed工具。
以上即为Python文件特定行插入和替换的简单实例。如果大家有不明白的地方或者有更好的建议,欢迎前往留言区或社区提问和交流。感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









