open two files at once

Discussion in 'Python' started by robek, Aug 21, 2010.

  1. robek

    robek Guest

    hi,
    what is the simplest way to open two files (one for reading and 2nd for
    writing) ?
    i usually do:
    with open('1') as f1:
    with open('2','w') as f2:
    for i in f1: do something with i
    f2.write(i)

    is there a simpler/better way to do this ?
     
    robek, Aug 21, 2010
    #1
    1. Advertising

  2. robek

    Peter Otten Guest

    robek wrote:

    > what is the simplest way to open two files (one for reading and 2nd for
    > writing) ?
    > i usually do:
    > with open('1') as f1:
    > with open('2','w') as f2:
    > for i in f1: do something with i
    > f2.write(i)
    >
    > is there a simpler/better way to do this ?


    Yours is the best way to do it in Python 2.6. In particular, don't use
    contextlib.nested():

    http://docs.python.org/library/contextlib.html#contextlib.nested

    Python 2.7 allows writing

    with open(source) as f1, open(dest, "w") as f2:
    # ...

    saving you one level of indentation.

    Peter
     
    Peter Otten, Aug 21, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Adam
    Replies:
    5
    Views:
    444
    Jim Cheshire
    Jul 29, 2003
  2. GenxLogic
    Replies:
    3
    Views:
    1,371
    andrewmcdonagh
    Dec 6, 2006
  3. chandan
    Replies:
    0
    Views:
    996
    chandan
    Nov 17, 2008
  4. chandan
    Replies:
    0
    Views:
    526
    chandan
    Nov 17, 2008
  5. Gancy
    Replies:
    4
    Views:
    241
    Rasto Levrinc
    Feb 3, 2005
Loading...

Share This Page