Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File open: Is this bad Python style?

To read contents of a file:

data = open(filename, "r").read()

The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing.

EDIT: This has actually bitten me in a project I wrote - it prompted me to ask this question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.

like image 981
Claudiu Avatar asked Sep 03 '09 14:09

Claudiu


People also ask

What does open file mean in Python?

Definition and Usage The open() function opens a file, and returns it as a file object.

What is the correct way to open a file Python?

Opening Files in Python Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.

Do I need to close file with open Python?

Yes, because otherwise you might leak resources. From the Python docs: When you're done with a file, call f. close() to close it and free up any system resources taken up by the open file.

Why is it best to open a file with with in Python?

With the “With” statement, you get better syntax and exceptions handling. “The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.” In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.


1 Answers

Just for the record: This is only slightly longer, and closes the file immediately:

from __future__ import with_statement

with open(filename, "r") as f:
    data = f.read()
like image 67
0x89 Avatar answered Oct 17 '22 08:10

0x89