In Python, how can I open a file and read it on one line and still be able to close the file after that?

I encountered a problem during this exercise.

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)

# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()

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

raw_input()

output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
input.close()

The line # we could do these two on one line too, how?is what scares me. The only answer I could come up with was this:

indata = open(from_file).read()

This performed as I wanted, but I need to remove:

input.close()

since the input variable no longer exists. How then can I perform this closed operation?

How would you solve this?

+5
source share
6 answers

The preferred way to work with resources in python is to use context managers :

 with open(infile) as fp:
    indata = fp.read()

The operator withtakes care of closing the resource and cleaning.

You can write this on one line if you want:

 with open(infile) as fp: indata = fp.read()

, python.

with:

with open(input, 'r') as infile, open(output, 'w') as outfile:
    # use infile, outfile

, , python.

+14
with open(from_file, 'r') as f:
  indata = f.read()

# outputs True
print f.closed
+2

, , input - , open, , .

, , , - script , . , , , , - with, , Python.

+2

script.

0
source

The following Python code will complete your task.

from contextlib import nested

with nested(open('input.txt', 'r'), open('output.txt', 'w')) as inp, out:
    indata = inp.read()
    ...
    out.write(out_data)
0
source

Just use a colon between the existing line of code ie

in_file = open(from_file); indata = in_file.read()

I think this is what you were.

0
source

All Articles