Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file

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?

like image 720
vaab Avatar asked Sep 16 '09 10:09

vaab


People also ask

How do I write an ascii file in Python?

You can write ASCII tables using the ascii. write() function. There is a lot of flexibility in the format of the input data to be written: NumPy structured array or record array.


1 Answers

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.

like image 119
Brian Avatar answered Sep 20 '22 13:09

Brian