1

我有一个文件如下

sys.test1.username = user1
sys.test1.pwd = 1234
sys.test2.username = user2
sys.test2.pwd = 1234

我想将 sys.test1.pwd 的密码更改为 sys.test1.pwd = 4321

读取文件

with open (tempfile, 'r') as tempFile:
            return self.parse_cfg (self, tempFile.readlines ())

这是搜索 sys.test1.pwd 并获取值。

def parse_cfg (self, lines):
        """ Parse ubnt style configuration into a dict"""
        ret_dict = {}
        for line in lines:
            line = line.strip () # remove new lines
            if not line: continue # skip empty lines


            key, value = line.split ('=') # key = value
            print "key %s" %key 

            if key == 'sys.test1.pwd':
                key = key.strip ()            
                value = value.strip ()

                # logic to parse mainkey.subkey.subkey structure into a dict
                keys = key.split ('.') 
                tempo = ret_dict
                for each in keys[:-1]:
                    tempo.setdefault (each, {})
                    tempo = tempo[each]
                tempo[keys[-1]] = value

                break

        return ret_dict

但我不知道如何将 sys.test1.pwd=4321 写入文件。请帮我

4

2 回答 2

1

我不确定你的确切问题是什么,所以我会尽量回答我的最佳理解。

您要将其写入同一个文件还是写入不同的文件?

基本上要写入文件,您需要打开具有写入权限的文件 -

termFileWrite = open (tempfile, 'w')

termFileWrite.write(yourText)

如果您询问以上述格式写入文件,那么它应该类似于:

myString = ""
for k,v in dict.iteritems():
    myString+=k+"="+v+"\n"
termFileWrite.write(myString)
于 2013-10-21T08:38:56.630 回答
1

这应该工作

import re

def searchReplace(file, search, replace):
    with open (file,'r') as f:
        f_content= f.read()
    # Re to search and replace
    f_content = (re.sub(search, replace, f_content))
    #write file with replaced content
    with open (file,'w') as f:
        f.write(f_content)


searchReplace("file.txt","sys.test1.pwd = 1234","sys.test1.pwd = 4321")
于 2013-10-21T08:56:29.903 回答