替换文件中的指定行
Replacing a specified line in File
我想搜索一个项目然后替换它的数量。是否可以对文件执行此操作?
文本文件示例:
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()打开文件并读取文件
- 将所有文件作为键值对存入字典
- 找到要替换其值的键。
- 就是这样。
我想搜索一个项目然后替换它的数量。是否可以对文件执行此操作?
文本文件示例:
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()打开文件并读取文件
- 将所有文件作为键值对存入字典
- 找到要替换其值的键。
- 就是这样。