Python 如何通过新输入交换文件列表中的参数

Python 如何通过新输入交换文件列表中的参数,python,python-3.x,Python,Python 3.x,第一个代码在列表中搜索字符串后找到它,需要新的输入,要求我提供新的参数,收到后,需要与新的参数交换 示例: 约翰|阿道夫|约翰|约翰123阿达|库珀|阿达克|阿达123 input_1=Adolfo搜索input_2=列表中的新参数交换 带输入_1 新名单: John |新参数(输入| 2)| johna | john123 ada | Cooper | adac | ada123 不需要解析或拆分字符串。只需获取第一个参数: print("\nParameter you want to cha

第一个代码在列表中搜索字符串后找到它,需要新的输入,要求我提供新的参数,收到后,需要与新的参数交换

示例:

约翰|阿道夫|约翰|约翰123阿达|库珀|阿达克|阿达123

input_1=Adolfo搜索input_2=列表中的新参数交换 带输入_1

新名单:

John |新参数(输入| 2)| johna | john123 ada | Cooper | adac | ada123


不需要解析或拆分字符串。只需获取第一个参数:

print("\nParameter you want to change?")
parameter = input(">> ")

someFile = open("komad_namestaja.txt", "r")

for line in someFile.readlines():
    line = line.split("|")
打开并读取文件:

parameter = input('Parameter you want to change: ')

编辑以保存到文件

唯一的更改是在替换字符串中的参数并重写到文件后清除打开的文件

以下是包含上述内容的完整代码:

if parameter in f:
    newWord = input('Second parameter to replace with: ')
    newString = f.replace(parameter, newWord)
else:
    print('%s not found.' % parameter)
parameter=input('要更改的参数:')
f=开放(,'r+'))
contents=f.read()

f、 seek(0)#祝你好运,你为我节省了两天时间,非常感谢。@BullzY:如果答案有帮助,请记住接受它。@m_callens:嗯……我更改了代码格式。始终使用4个空格来格式化代码。这不起作用,参数没有保存到文件中(替换为旧的)@BullzY根据您所说的,参数将从终端中的用户输入中给出。这不是真的吗?编辑:哦,您从未指定要将新字符串重新保存到文件中。
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