0

I am trying to read from one file and write to another file using:

with open('example2') as inpf, open('outputrt','w') as outf:  
    for l in inpf:
        outf.write(l)  

But I am getting a syntax error at the line 1 i.e.

"with open('example2') as inpf, open('outputrt','w') as outf:" pointing at "inpf,"

My python version is 2.6. Is there an error in syntax?

jamylak
  • 128,818
  • 30
  • 231
  • 230
learner
  • 325
  • 2
  • 3
  • 9
  • Take a look at http://stackoverflow.com/questions/3791903/which-python-version-need-from-future-import-with-statement (short version: add `from __future__ import with_statement` at the top of your script). – Hugh Bothwell May 25 '12 at 00:01
  • 1
    If this is really your code, you would be better off with `shutil.copyfile`. – sberry May 25 '12 at 00:02
  • This code works for me .. Python 2.7.2 – Ansari May 25 '12 at 00:03
  • with is working fine if i give only the part till inpf, but if i give it together with output file in write mode, i am geting syntax error – learner May 25 '12 at 00:06

2 Answers2

2

That syntax is only supported in 2.7+.
In 2.6 you can do:

import contextlib

with contextlib.nested(open('example2'), open('outputrt','w')) as (inpf, outf):  
    for l in inpf:
        outf.write(l) 

Or it might look cleaner to you to do this (this would be my preference):

with open('example2') as inpf:
    with open('outputrt','w') as outf:  
        for l in inpf:
            outf.write(l)  
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
0

In python versons <= 2.6, you can use

inPipe = open("example2", "r")
outPipe = open("outputrt", "w")
for k in inPipe:
    outPipe.write(k)
ncmathsadist
  • 4,684
  • 3
  • 29
  • 45