是否可以修改文件中的行? [英] Is it possible to modify lines in a file in-place?
问题描述
有没有可能一行一行地解析一个文件,并在通过这些行的同时编辑一个行?
< blockquote>
是否可以逐行解析一个文件,并在编辑行的同时进行编辑?
可以使用备份文件模拟stdlib的 下面是一个示例脚本,用于删除不满足 例子: 完成 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 Here's an example script that removes lines that do not satisfy Example: On completion 这篇关于是否可以修改文件中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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>
fileinput
module does.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.txt
and second_file.txt
files will contain only lines that satisfy some_condition()
predicate.