gpt4 book ai didi

python - 是否可以就地修改文件中的行?

转载 作者:IT老高 更新时间:2023-10-28 20:28:38 24 4
gpt4 key购买 nike

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

最佳答案

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

可以使用备份文件作为stdlib的fileinput module进行模拟可以。

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

#!/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() 谓词的行。

关于python - 是否可以就地修改文件中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5453267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com