print("nParameter you want to change?")
parameter = input(">> ")
someFile = open("komad_namestaja.txt", "r")
for line in someFile.readlines():
line = line.split("|")
找到它后,首先代码在列表中搜索字符串,需要新的输入,要求我输入新参数,接收后,需要与新参数交换。
例:
约翰|阿道夫|约翰娜|约翰123 阿达|库珀|阿达克|阿达123
input_1 = 阿道夫搜索 input_2 = 列表中的新参数交换 与input_1
新列表 :
约翰|新参数(input_2(|约翰娜|约翰123 ada|库珀|阿达克|阿达123
无需解析或拆分字符串。只需获取第一个参数:
parameter = input('Parameter you want to change: ')
打开并读取文件:
f = open(<filename>, 'r').read()
如果找到参数,则获取第二个参数并替换它们:
if parameter in f:
newWord = input('Second parameter to replace with: ')
newString = f.replace(parameter, newWord)
else:
print('%s not found.' % parameter)
编辑以保存到文件
唯一的更改是在替换字符串中的参数并重写到文件后清除打开的文件...
以下是包括上述内容的完整代码:
parameter = input('Parameter you want to change: ')
f = open(<filename>, 'r+')
contents = f.read()
f.seek(0) #<-- reset the cursor position in file to 0
if parameter in contents:
newWord = input('Second parameter to replace with: ')
newString = contents.replace(parameter, newWord)
else:
print('%s not found.' % parameter)
newString = contents
f.truncate() #<-- clear the file
f.write(newString) #<-- write the new string to the file
f.close() #<-- close the file to end