是否可以就地修改文件中的行? [英] Is it possible to modify lines in a file in-place?

查看:23
本文介绍了是否可以就地修改文件中的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以逐行解析文件,并在遍历行时就地编辑一行?

Is it possible to parse a file line by line, and edit a line in-place while going through the lines?

推荐答案

是否可以逐行解析文件,并在遍历行时就地编辑一行?

Is it possible to parse a file line by line, and edit a line in-place while going through the lines?

可以使用备份文件作为 stdlib 的 fileinput 模块进行模拟 确实如此.

It can be simulated using a backup file as stdlib's fileinput module does.

这是一个示例脚本,它从命令行或 stdin 给出的文件中删除不满足 some_condition 的行:

Here's an example script that removes lines that do not satisfy some_condition from files given on the command line or stdin:

#!/usr/bin/env python
# grep_some_condition.py
import fileinput

for line in fileinput.input(inplace=True, backup='.bak'):
    if some_condition(line):
        print line, # this goes to the current file

示例:

$ python grep_some_condition.py first_file.txt second_file.txt

完成后first_file.txtsecond_file.txt 文件将只包含满足some_condition() 谓词的行.

On completion first_file.txt and second_file.txt files will contain only lines that satisfy some_condition() predicate.

这篇关于是否可以就地修改文件中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆