Python 替换文件中的指定行
我想搜索一个项目,然后替换它的数量。可以对文件执行此操作吗 文本文件示例:Python 替换文件中的指定行,python,file,replace,Python,File,Replace,我想搜索一个项目,然后替换它的数量。可以对文件执行此操作吗 文本文件示例: apples 10.2 banana 20.5 oranges 10 因此,当我输入“banana”时,我希望能够将20.5更新为一个不同的数字。由于您尚未发布您迄今为止所做的事情,我只能给您一些提示 # open the file -> check out python's open() function and the different modes , w+ opens the file for b
apples
10.2
banana
20.5
oranges
10
因此,当我输入“banana”时,我希望能够将20.5更新为一个不同的数字。由于您尚未发布您迄今为止所做的事情,我只能给您一些提示
# open the file -> check out python's open() function and the different modes , w+ opens the file for both writing ad reading
.... file_handle = open("yourtextfile", "w+")
# check out readlines() function , it gives you back a list of lines , in the order of from the first line to the last
..... the_lines = file_handle.readlines()
# remove newline '\n' from every element in the list
..... new_list = [elem.strip() for elem in the_lines]
# look for existence of 'banana' in the new_list and going by the structure of the file you just posted edit the value next to the banana i.e 20.5
.... for item in new_list:
if item == "banana":
index = new_list.index(item) + 1
new_list[index] = new_value
#add the newlines back
new_string = '\n'.join(new_list)
file_handle.write(new_string)
file_handle.close()
break
- 用open()打开文件并读取该文件
- 将所有文件作为键值对放入字典
- 找到要替换其值的键
- 就这样