[Solved] how to write this in one line in python [closed]


Python’s with statement comes handy here. And its good habit to use it when you’re working with files, as it takes care of tearing down the objects, and catching exceptions too.

You can read about it in the documentation.

And here is how you would use with in your program:

from sys import argv
from os.path import exists

script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)

with open(from_file) as input, open(to_file, 'w') as output:

    print "The input file is %d bytes long" % len(input.read())
    print "Does the output file exist? %r" % exists(to_file)
    raw_input("Ready, hit RETURN to continue, CTRL-C to abort.")

    output.write(input.read())
    print "Alright, all done."

One liner

with open(from_file) as in, open(to_file, 'w') as o: o.write(in.read())

Tip:
Writing all this code in one line would decrease its readability.
However, python supports ; as line terminator.

So you can do something like this:

print foo(); print bar(); print baz();

But do remember python’s colon : operator has more precedence than ;. Thus if we write –

if True: print foo(); print bar();

Here either all of the print statements will execute or none.

solved how to write this in one line in python [closed]