我正在尝试使用 Python FileInput 类编辑文本文件。首先,我将需要写入的行存储在字典中。然后我遍历该字典,如果字典[key] 匹配该行中的任何行,我将用字典键值对替换该行。如果文件中不存在字典[key],那么我想在文件末尾写下该行;但是,这最后一部分不起作用,也没有写入文件。
这是当前代码的样子:
def 文件编辑(属性,dst_path):
for key in properties.iterkeys():
for line in fileinput.FileInput(dst_path, inplace=1):
if str(key) + '=' in line: #<==== This works
print key + '=' + properties[key] #<==== This works
#The below condition checks that if the Dictionary[Key] is not there, then just print the line
elif str(key) + '=' not in line and re.findall(r'[a-zA-Z0-9=:]+',line) is not None:
print line.strip() #<==== This seems to work
else: #<============THIS DOES NOT WORK
print key + '=' + properties[key] #<============THIS DOES NOT WORK
fileinput.close()
file_edit({'新键':'一些值','现有键':'新值'},SomeTextFile.TXT)
任何输入将不胜感激。
谢谢!