Tuesday 15 April 2014

python - Using 'r+' mode to overwrite a line in a file with another line of the same length -



python - Using 'r+' mode to overwrite a line in a file with another line of the same length -

i have file called vegetables:

carrots apples_ cucumbers

what want open file in python, , modify in-place, without overwriting big portions of file. specifically, want overwrite apples_ lettuce, such file this:

carrots lettuce cucumbers

to this, i've been told utilize 'r+' mode. however, don't know how overwrite line in place. possible? solutions familiar involve caching entire file, , overwriting entire file, little amendment. best option?

important note: replacement line same length original line.

for context: i'm not concerned file on vegetables. rather, have textfile of 400 lines need create revisions every 2 minutes. have script this, want more efficiently.

an reply works example

with open("vegetables","r+") t: info = t.read() t.seek(data.index("apples_")) t.write("lettuce")

although, might not worth complicate things this,

it's fine read entire file, , overwriting entire file, aren't going save much doing example

note: works if has same length original text replacing

edit1: (possibly bad) illustration replace match:

import re open("test","r+") t: info = t.read() m in re.finditer("apples_", data): t.seek(m.start()) t.write("lettuce")

edit2: little more complex using closure can check multiple words replace

import re def get_find_and_replace(f): """f --> file open r+ mode""" info = f.read() def find_and_replace(old, new): m in re.finditer(old, data): f.seek(m.start()) f.write(new) homecoming find_and_replace open("test","r+") f: find_and_replace = get_find_and_replace(f) find_and_replace("apples_","lettuce") #find_and_replace(...,...) #find_and_replace(...,...)

python python-2.7

No comments:

Post a Comment