如何通过新inpu交换文件列表中的参数

2024-04-27 09:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

for line in someFile.readlines():
    line = line.split("|")

首先代码在列表中搜索字符串后找到它,需要新的输入来询问我新的参数,收到后,需要和新的参数交换

示例:

John|Adolfo|johna|john123 ada|Cooper|adac|ada123

input_1 = Adolfo searching input_2 = new parameter exchange in list with input_1

新列表:

John|new parameter(input_2)|johna|john123 ada|Cooper|adac|ada123


Tags: in列表input参数parameterlinejohnsomefile
1条回答
网友
1楼 · 发布于 2024-04-27 09:11:08

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

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

相关问题 更多 >