В Python, как я могу открыть файл и прочитать его в одной строке, и все же иметь возможность закрыть файл после этого?

Работая над этим упражнением, я столкнулся с проблемой.

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()

Линия# we could do these two on one line too, how? это то, что меня смущает. Единственный ответ, который я мог придумать, был:

indata = open(from_file).read()

Это выполнено так, как я хотел, но требует, чтобы я удалил:

input.close()

поскольку входная переменная больше не существует. Как тогда я могу выполнить эту близкую операцию?

Как бы вы решили это?

Ответы на вопрос(6)

Ваш ответ на вопрос