簡體   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