Usage of file and open in Python

Source: Internet
Author: User
Tags flush readline in python

What's the difference between file and open?

File is a class, and when opened with the Open function, returns a file object.
file1 = File ("Aa.txt")

File2 = open ("Aa.txt") #这个时候返回的是跟file1一样的对象, can be read to Aa.txt, modify.

Temporarily found that seemingly not much difference, the habit of like to use open.

Python 2 is basically no different. There's no file in Python 3.

In Python 2, file is a document object. Open is the built-in function that returns the newly created file object, which is equivalent to:

def open (*args, **kwargs):
Return file (*args, **kwargs)
Its true definition is:

Static Pyobject *
Builtin_open (Pyobject *self, Pyobject *args, Pyobject *kwds)
{
Return Pyobject_call ((pyobject*) &pyfile_type, args, Kwds);
}

So file is also able to create files.

File and open usages


Help (file) help (Open)

The old rules first look at the built-in help document how to describe file and open, after all, the official document is the most direct and accurate description.

Help on class file in module __builtin__:

class file (object)
| File (name[, mode[, Buffering]])-> file object
|
|  Open a file. The mode can be is ' r ', ' W ' or ' A ' for reading (default),
|  Writing or appending. The file would be created if it doesn ' t exist
| When opened for writing or appending; It'll be truncated when
|  Opened for writing. Add a ' B ' to the "mode for binary files."
| Add a ' + ' to "mode to allow simultaneous reading and writing.
| If The buffering argument is given, 0 means unbuffered, 1 means line
|  Buffered, and larger numbers specify the buffer size. The preferred way
| To open a file are with the Builtin open () function.
| Add a ' U ' to "mode to open" file for input with universal newline
|  Support. Any line ending in the input file would be seen as a ' \ n '
|  In Python. Also, a file so opened gains the attribute ' newlines ';
| The value is one of None (no newline read yet),
| ' \ r ', ' \ n ', ' \ r \ n ' or a tuple containing all the newline types seen.
Simply put, file is a class that uses file (' file_name ', ' r+ ') to open files, return a filename object, open the file in write mode, and it will be created. But it is more recommended to use the built-in function open () to open a file, so let's take a look at the introduction to open ():

Help on built-in function open in module __builtin__:

Open (...)
Open (name[, mode[, buffering])-> file object

The Open a file using the file () type, returns a file object. This is the
Preferred way to open a file. File.__doc__ for further information.
(end)
First Open is a built-in function, which is open (' file_name ', mode, buffering), and the return value is also a file object, and similarly, opening a file in write mode will create a new one if it does not exist.

Working with instances

In [8]: f1 = open (' test.py ')                                                                                                                                                                               

In [9]: F1.
f1.close       f1.fileno      f1.name         f1.readinto    f1.softspace   f1.writelines
f1.closed       f1.flush       f1.newlines    f1.readline    f1.tell        f1.xreadlines
f1.encoding     f1.isatty      f1.next        f1.readlines   f1.truncate   
f1.errors      f1.mode         f1.read        f1.seek         f1.write      

In [9]: F1.rea
F1.read F1.readinto F1.readline F1.readlines

In [9]: F1.readli
F1.readline F1.readlines

In [9]: F1.readlines ()
OUT[9]:
[' Import logging\n ',
' \ n ',
"Logging.basicconfig (filename= ' Test.log ', level=logging.info) \ n",
"Logging.info (' started ') \ n",
"Print ' x ' + 1\n",
"Logging.info (' finished ') \ n"]

In [ten]: f1.cl
F1.close f1.closed

In [ten]: F1.close ()

In [one]: F2 = file (' test.py ')                                                                                                                                                                              

in [[]: F2.
f2.close       f2.fileno      f2.name         f2.readinto    f2.softspace   f2.writelines
f2.closed       f2.flush       f2.newlines    f2.readline    f2.tell        f2.xreadlines
f2.encoding     f2.isatty      f2.next        f2.readlines   f2.truncate   
f2.errors      f2.mode         f2.read        f2.seek         f2.write      

in [[]: F2.read
F2.read F2.readinto F2.readline F2.readlines

in [[]: F2.readli
F2.readline F2.readlines

in [[]: F2.readlines ()
OUT[12]:
[' Import logging\n ',
' \ n ',
"Logging.basicconfig (filename= ' Test.log ', level=logging.info) \ n",
"Logging.info (' started ') \ n",
"Print ' x ' + 1\n",
"Logging.info (' finished ') \ n"]

in [+]: f2.cl
F2.close f2.closed

in [[]: F2.closed ()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-24c97e0e079e> in <module> ()
----> 1 f2.closed ()

TypeError: ' bool ' object is not callable

in [/]: f2.closed
OUT[14]: False

in [[]: F2.close ()

# Open files that don't exist

in [[]: F3 = File (' txt.txt ', ' r+ ')
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-18-3e9262877eea> in <module> ()
----> 1 f3 = File (' txt.txt ', ' r+ ')

IOError: [Errno 2] No such file or directory: ' Txt.txt '

in [[]: F3 = File (' txt.txt ', ' w+ ')
Can be seen to use when the difference is not very small, but note that Py3 has no file~ this may also be the recommended use of open a very important reason for it

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.