简体   繁体   中英

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? 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 :

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

The with statement takes care of closing the resource and cleaning up.

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.

You can also open multiple files in a with block:

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.

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.

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.

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

The following Python code will accomplish your goal.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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