0

Suppose I have two txt files, in.txt and out.txt.

in.txt:

Mary is Passed 
Jane is Failed

out.txt:

Status of Mary: 'N/A'
Status of Jane: 'N/A'

I want to write Python code which reads in.txt and replaces the 'N/A' with Passed for Mary and Failed for Jane in out.txt.

I could manage to write at the end of the line of out.txt but not at 'N/A'

Jason Sundram
  • 12,225
  • 19
  • 71
  • 86
Sam
  • 79
  • 2
  • 10

2 Answers2

0

See my answer here on a related question: Deleting a line in a file

Bascially, editing the bytes in the middle of a file is no fun. You should just read the file in memory and overwrite it at the end if it's not too large, or use something like tempfile if it is real large.

Community
  • 1
  • 1
korylprince
  • 2,969
  • 1
  • 18
  • 27
0
import re

...

outf = open('myout', 'r+')
inf = open('infile', 'r')
outdata = outf.read()
for line in inf:
    outdata = re.sub("(?<=Status of %s: )'N/A'" % line.strip().split()[0], line.strip().split()[2], outdata)
outf.write(outdata)
outf.close()
inf.close()
kirbyfan64sos
  • 10,377
  • 6
  • 54
  • 75
  • I think this will work but this traceback appears when I run this code. Traceback (most recent call last): File "./stack.py", line 11, in outdata = re.sub("(?<=Status of %s: )'N/A'" % line.strip().split()[0], line.strip().split()[2]) TypeError: sub() takes at least 3 arguments (2 given) – Sam Nov 13 '13 at 03:46