Skip to content Skip to sidebar Skip to footer

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_f

Solution 1:

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.


Solution 2:

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

# outputs True
print f.closed

Solution 3:

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.


Solution 4:

The file will be closed automatically and safely when your script completes.


Solution 5:

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)

Post a Comment for "In Python, How Can I Open A File And Read It On One Line, And Still Be Able To Close The File Afterwards?"