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

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

问题描述

有没有可能一行一行地解析一个文件,并在通过这些行的同时编辑一个行?

解决方案

< blockquote>

是否可以逐行解析一个文件,并在编辑行的同时进行编辑?


可以使用备份文件模拟stdlib的 fileinput <

下面是一个示例脚本,用于删除不满足 some_condition 从命令行给出的文件或 stdin

 # !/ usr / bin / env python 
#grep_some_condition.py
import fileinput
$ b $ for line in fileinput.input(inplace = True,backup ='。bak'):
如果some_condition(line):
print line,#this goes to the current file

例子:

  $ python grep_so me_condition.py first_file.txt second_file.txt 

完成 first_file.txt second_file.txt 文件将仅包含满足 some_condition()谓词的行。 p>

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?

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

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

Example:

$ python grep_some_condition.py first_file.txt second_file.txt

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

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

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