繁体   English   中英

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

[英]In Python, how can I open a file and read it on one line, and still be able to close the file afterwards?

在完成这个练习的过程中,我遇到了一个问题。

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

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

你怎么解决这个问题?

在python中使用资源的首选方法是使用上下文管理器

 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的时候,我回答了同样的问题

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

# outputs True
print f.closed

您应该将此视为一种练习,以便理解input只是open返回的名称,而不是您应该以较短的方式进行的建议。

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

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

以下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)

只需在现有代码行之间使用半冒号即

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM