简体   繁体   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?

While working through this exercise I ran into a problem. 在完成这个练习的过程中,我遇到了一个问题。

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? 线# we could do these two on one line too, how? is what's confusing me. 令我困惑的是什么。 The only answer I could come up with was: 我能想到的唯一答案是:

indata = open(from_file).read()

This performed the way I wanted to, but it requires me to remove: 这按照我想要的方式执行,但它要求我删除:

input.close()

as the input variable no longer exists. 因为输入变量不再存在。 How then, can I perform this close operation? 那么,我怎么能执行这种近距离操作?

How would you solve this? 你怎么解决这个问题?

The preferred way to work with resources in python is to use context managers : 在python中使用资源的首选方法是使用上下文管理器

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

The with statement takes care of closing the resource and cleaning up. with语句负责关闭资源并清理。

You could write that on one line if you want: 如果你愿意,你可以写上一行:

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

however, this is considered bad style in python. 但是,这在python中被认为是不好的风格。

You can also open multiple files in a with block: 您还可以在with块中打开多个文件:

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

Funny enough, I asked exactly the same question back when I started learning python. 有趣的是,当我开始学习python的时候,我回答了同样的问题

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

# outputs True
print f.closed

You should think of this as an exercise to understand that input is just a name for what open returns rather than as advice that you ought to do it the shorter way. 您应该将此视为一种练习,以便理解input只是open返回的名称,而不是您应该以较短的方式进行的建议。

As other answers mention, in this particular case the problem you've correctly identified isn't that much of an issue - your script closes fairly quickly, so any files you open will get closed fairly quickly. 正如其他答案所提到的,在这种特殊情况下,您正确识别的问题不是问题 - 您的脚本会很快关闭,因此您打开的所有文件都会很快关闭。 But that isn't always the case, and the usual way of guaranteeing that a file will close once you're done with it is to use a with statement - which you will find out about as you continue with Python. 但情况并非总是这样,并且一旦完成文件就保证文件将关闭的通常方法是使用with语句 - 当你继续使用Python时,你会发现它。

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

The following Python code will accomplish your goal. 以下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)

Just use a semi colon in between your existing code line ie 只需在现有代码行之间使用半冒号即

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

I think his is what you were after.. 我认为他就是你所追求的......

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

暂无
暂无

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

相关问题 如何在 python 中打开一个 csv 文件,一次读取一行,而不将整个 csv 文件加载到内存中? - How can I open a csv file in python, and read one line at a time, without loading the whole csv file in memory? 如何在 Python 中打开图像并在之后关闭? - How to open an image in Python and close afterwards? 我可以用 Python 在一行中读写文件吗? - Can I read and write file in one line with Python? 在 1 行代码中打开读取和关闭文件 - open read and close a file in 1 line of code 如何使用Python从文件中读取零行 - How can I read a line of zeroes from a file with Python 我如何从 python 中的特定行读取文本文件? - How i can Read text file from a specific line in python? 如何在一行中将输入写入文件并将多个输入存储到文件中并能够读取它们? - How do I write input to files in one line and store multiple inputs to the file and be able to read them? Python打开一个文件并正在读取它的数据,为什么python仍然可以读取它的数据,即使我删除了这个文件? - Python opened one file and is reading its data, why python still can read its data even I delete this file? 如何使用python更改文本文件中的一行 - How can I change one line in text file with python Python gevent我没有看到猴子修补默认文件的打开/读取/写入/关闭,如何在gevent异步中制作文件io - Python gevent I don't see monkey patched the default file open/read/write/close, how to make file io in gevent async
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM