Python利用fileinput实现文件特定行插入与替换

键盘旁的猫
键盘旁的猫
发布时间:2026-10-13| 4人浏览过
原创

本文详解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文件特定行插入和替换的简单实例。如果大家有不明白的地方或者有更好的建议,欢迎前往留言区或社区提问和交流。感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。