Python - When to use file vs open

What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)


Asked by: Madaline917 | Posted: 05-10-2021






Answer 1

You should always use open().

As the documentation states:

When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)").

Also, file() has been removed since Python 3.0.

Answered by: Kellan786 | Posted: 06-11-2021



Answer 2

Two reasons: The python philosophy of "There ought to be one way to do it" and file is going away.

file is the actual type (using e.g. file('myfile.txt') is calling its constructor). open is a factory function that will return a file object.

In python 3.0 file is going to move from being a built-in to being implemented by multiple classes in the io library (somewhat similar to Java with buffered readers, etc.)

Answered by: Kevin411 | Posted: 06-11-2021



Answer 3

file() is a type, like an int or a list. open() is a function for opening files, and will return a file object.

This is an example of when you should use open:

f = open(filename, 'r')
for line in f:
    process(line)
f.close()

This is an example of when you should use file:

class LoggingFile(file):
    def write(self, data):
        sys.stderr.write("Wrote %d bytes\n" % len(data))
        super(LoggingFile, self).write(data)

As you can see, there's a good reason for both to exist, and a clear use-case for both.

Answered by: Connie407 | Posted: 06-11-2021



Answer 4

Functionally, the two are the same; open will call file anyway, so currently the difference is a matter of style. The Python docs recommend using open.

When opening a file, it's preferable to use open() instead of invoking the file constructor directly.

The reason is that in future versions they is not guaranteed to be the same (open will become a factory function, which returns objects of different types depending on the path it's opening).

Answered by: Alina706 | Posted: 06-11-2021



Answer 5

Only ever use open() for opening files. file() is actually being removed in 3.0, and it's deprecated at the moment. They've had a sort of strange relationship, but file() is going now, so there's no need to worry anymore.

The following is from the Python 2.6 docs. [bracket stuff] added by me.

When opening a file, itโ€™s preferable to use open() instead of invoking this [file()] constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)

Answered by: Marcus158 | Posted: 06-11-2021



Answer 6

According to Mr Van Rossum, although open() is currently an alias for file() you should use open() because this might change in the future.

Answered by: Patrick868 | Posted: 06-11-2021



Similar questions

python - file open and file save

I am having problems finding the right documentation on how to open a file in a given folder for reading and how to save an output file to a given folder. I would appreciate if someone could explain it to me or point in the right direction. I have to open a file of tagged words, one word and its tag per line, that I will use to check my code, then I will have to create a similar file, using a text file and my code....


Python XML File Open

I am trying to open an xml file and parse it, but when I try to open it the file never seems to open at all it just keeps running, any ideas? from xml.dom import minidom Test_file = open('C::/test_file.xml','r') xmldoc = minidom.parse(Test_file) Test_file.close() for i in xmldoc: print('test') The file is 180.288 KB, why does it never make it to the print portion?


python - Know Which file is open

I'm reading from a folder of txt files, in a loop in this way: path = './input/*.txt' files=glob.glob(path) for file in files: with open (file, 'rt') as f: fstr= f.read() Is there a way to know on which file the program is atm? I want to print it. Thanks


How to get file to open with python app I made

For the past month I've been writing a desktop application for MacOS using Python. It requires opening files and saving compressed data to them. This application creates files using a my own made up extension, so the files are not usable for for other applications. I have almost everything figured out. However, I want to make it so that I can right click on a file with the extension and open it with my python application. ...


PYTHON file open using list

file_1=open("file.txt") lis=[] for i in file_1: lis=i print(lis) print(lis) I want to keep my text file into the list, but after for loop the list becomes empty


How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.


python name a file same as a lib

i have the following script import getopt, sys opts, args = getopt.getopt(sys.argv[1:], "h:s") for key,value in opts: print key, "=>", value if i name this getopt.py and run it doesn't work as it tries to import itself is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? Solution based ...


Python FTP Most Recent File

This question already has answers here:


XML file using Python

I have made a XML file using python. How can I retrieve an element from it? Will you help me with the code? Also I need to have my output (i.e. element of each attribute come in separate lines in that particular XML file).


file - What does 'wb' mean in this code, using Python?

Code: file('pinax/media/a.jpg', 'wb')


run python file

i dont have any experience in python programming but I get to run python file is there any one to help me pls here is the file content >>>>>>>>>>>>>> #!/usr/local/bin/python """ Based on: http://wxpsvg.googlecode.com/svn/trunk/svg/pathdata.py According to that project, this file is licensed under the LGPL """ try: from pyparsing import (ParserElement, Liter...


python - How to get self file name

This question already has answers here:


how add new line in CSV file using python

I have a csv file that contains time (hh:mm:ss) and date (mm/dd/yyyy) fields, and sixteen more fields. Generally the time field display time every 30'', but sometime the separation might be more (minutes or even hours). For instance: 1/27/2011 12:10:00 1/27/2011 12:10:30 1/27/2011 12:11:00 1/27/2011 12:15:00 I need to add new lines (as many as the gap between them) every...


python - How do I get the file / key size in boto S3?

There must be an easy way to get the file size (key size) without pulling over a whole file. I can see it in the Properties of the AWS S3 browser. And I think I can get it off the "Content-length" header of a "HEAD" request. But I'm not connecting the dots about how to do this with boto. Extra kudos if you post a link to some more comprehensive examples than are in the


pdf file with python

How can search a word or a line in a pdf file? Is there an existing module to do that by being concise? Thank you in advance,


python - What's the best Django search app?


How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.


python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.


python - What is the best way to copy a list?

This question already has answers here:


python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...


How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?


ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...


python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.


python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?


python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top