Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 666
yoonsi Avatar asked Jun 08 '12 09:06

yoonsi


People also ask

How can you read an entire file and get each line?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

How do you read a file from a specific line in Python?

Use readlines() to Read the range of line from the File You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python. We read the entire file using this way and then pick specific lines from it as per our requirement.


1 Answers

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.

like image 139
georg Avatar answered Sep 29 '22 09:09

georg