1

次のようなファイルがあります

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

sys.test1.pwd の 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 に答える