在Python中,如何打开文件并在一行中读取它,之后仍能关闭文件?

时间:2012-06-08 09:20:28

标签: 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()

因为输入变量不再存在。那么,我怎么能进行这种近距离操作呢?

你会如何解决这个问题?

7 个答案:

答案 0 :(得分:14)

在python中使用资源的首选方法是使用context managers

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

with语句负责关闭资源并进行清理。

如果你愿意,你可以在一行上写下:

 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时,我回复了exactly the same question

答案 1 :(得分:2)

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

# outputs True
print f.closed

答案 2 :(得分:2)

您应该将此视为一项练习,以了解input只是open返回的名称,而不是您应该执行此操作的建议更短方式。

正如其他答案所提到的,在这种特殊情况下,您正确识别的问题不是问题 - 您的脚本会很快关闭,因此您打开的所有文件都会很快关闭。但情况并非总是这样,并且一旦完成文件就保证文件将关闭的通常方法是使用with语句 - 在继续使用Python时,您会发现这些语句。

答案 3 :(得分:0)

脚本完成后,文件将自动安全关闭。

答案 4 :(得分:0)

以下Python代码将实现您的目标。

from contextlib import nested

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

答案 5 :(得分:0)

只需在现有代码行之间使用分号,即

{{1}}

我认为他就是你所追求的......

答案 6 :(得分:0)

in_file = open(from_file).read(); out_file = open(to_file,'w').write(in_file)