替换File中的特定行

时间:2015-02-26 03:40:15

标签: python file replace

我想搜索一个项目,然后替换它的数量。是否可以对文件进行操作?

文本文件示例:

apples
10.2
banana
20.5
oranges
10

所以当我输入" banana"我希望能够将20.5更新为不同的数字。

2 个答案:

答案 0 :(得分:0)

因为到目前为止你还没有发布你所做的事情,所以我只能给你指点;

    # 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

答案 1 :(得分:0)

  • 使用open()打开文件并读取文件
  • 将所有文件作为键值对放入字典中。
  • 找到要替换其值的键。
  • 就是这样。