how to get content of a small ascii file in python?

Question:

Let’s say we want to implement an equivalent of the PHP’s file_get_content.

What is the best practice? (elegant and reliable)

Here are some proposition, are they correct?

using with statement:

def file_get_contents(filename):
    with file(filename) as f:
        s = f.read()
    return s

is using standard open() safe?

def file_get_contents(filename):
    return open(filename).read()

What happens to file descriptor in either solution?

Asked By: vaab

||

Answers:

with will make sure that the file is closed when the block is left.

In your second example, the file handle might remain open (Python makes no guarantee that it’s closed or when if you don’t do it explicitly).

Answered By: Aaron Digulla
import os

def file_get_contents(filename):
  if os.path.exists(filename):
    fp = open(filename, "r")
    content = fp.read()
    fp.close()
    return content

This case it will return None if the file didn’t exist, and the file descriptor will be closed before we exit the function.

Answered By: amrhassan

Using the with statement is actually the nicest way to be sure that the file is really closed.

Depending on the garbage collector behavior for this task might work, but in this case, there is a nice way to be sure in all cases, so…

Answered By: Jonathan Ballet

In the current implementation of CPython, both will generally immediately close the file. However, Python the language makes no such guarantee for the second one – the file will eventually be closed, but the finaliser may not be called until the next gc cycle. Implementations like Jython and IronPython will work like this, so it’s good practice to explicitely close your files.

I’d say using the first solution is the best practice, though open is generally preferred to file. Note that you can shorten it a little though if you prefer the brevity of the second example:

def file_get_contents(filename):
    with open(filename) as f:
        return f.read()

The __exit__ part of the context manager will execute when you leave the body for any reason, including exceptions and returning from the function – there’s no need to use an intermediate variable.

Answered By: Brian

You can also use Python’s v3 feature:

>>> ''.join(open('htdocs/config.php', 'r').readlines())
"This is the first line of the file.nSecond line of the file"

Read more here http://docs.python.org/py3k/tutorial/inputoutput.html

Answered By: Argimko
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.