簡體   English   中英

使用Python搜索和替換特定字符串

[英]Searching and replacing specific string using Python

我正在嘗試編寫一個python腳本來搜索和替換文本文件中的特定字符串

例如,foo.txt是這樣的:

[section1]
option1=xyz
option2=abc

[section2]
option1=aaa
option2=bbb

我的目標是僅替換第2節中的option1和option2值,而不更改第1節中的任何內容,如下所示:

[section1]
option1=xyz
option2=abc

[section2]
option1=xxx
option2=zzz

我嘗試了pysed和許多其他方法,沒有骰子。 Python Guru有什么幫助嗎?

您可能會發現使用ConfigParser而不是搜索和替換更為容易:

#!/usr/bin/python                                                               
import ConfigParser                                                             
import os                                                                       

config = ConfigParser.ConfigParser()
config.readfp(open('foo.txt'))
config.set("section2", "option1", "xxx1")
config.set("section2", "option2", "yyy1")
# It's always better to write to a temporary file
# and then atomically replace the original:
config.write(open('foo.txt.new', "w"))
os.rename('foo.txt.new', 'foo.txt')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM