Python 2.7 如何将数据替换为文件的一行?
我有一个文件如下Python 2.7 如何将数据替换为文件的一行?,python-2.7,Python 2.7,我有一个文件如下 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.readline
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写入文件。请帮助我我不确定你的确切问题是什么,所以我会尽力回答你的问题 要将其写入同一个文件还是另一个文件 基本上,要写入文件,您需要打开具有写入权限的文件-
termFileWrite = open (tempfile, 'w')
termFileWrite.write(yourText)
如果您要求以上述格式写入文件,则应为:
myString = ""
for k,v in dict.iteritems():
myString+=k+"="+v+"\n"
termFileWrite.write(myString)
这应该行得通
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")
很好的解决方案。您可能希望为正则表达式传递原始字符串,以防万一。。。否则,如果你想按字面意思去做,我想你可以使用
.replace