{article Dive into Python}{title} {text} {/article}

Opening a File

Here is a list of all attributes related to file object:

AttributeDescription
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true otherwise.

Here is a list of the different modes of opening a file:

ModesDescription
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f = open("/music/_singles/kairo.mp3", "rb")
>>> f
<_io.BufferedReader name='/music/_singles/kairo.mp3'>
>>> f.mode
'rb'
>>> f.name
'/music/_singles/kairo.mp3'
>>>

The open method can take up to three parameters: a filename, a mode, and a buffering parameter. Only the
first one, the filename, is required; the other two are optional. If not specified, the file is opened for reading in
text mode. Here you are opening the file for reading in binary mode. (print open.__doc__ displays a
great explanation of all the possible modes.)

The open function returns an object (by now, this should not surprise you). A file object has several useful attributes.

The mode attribute of a file object tells you in which mode the file was opened.

The name attribute of a file object tells you the name of the file that the file object has open.

{source}
<!-- You can place html anywhere within the source tags -->
<pre class="brush:py;">

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f = open("/music/_singles/kairo.mp3", "rb")
>>> f
<_io.BufferedReader name='/music/_singles/kairo.mp3'>
>>> f.mode
'rb'
>>> f.name
'/music/_singles/kairo.mp3'
>>>


</pre>

<script language="javascript" type="text/javascript">
    // You can place JavaScript like this

</script>
<?php
    // You can place PHP like this

?>
{/source}


Reading Files

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f = open("/music/_singles/kairo.mp3", "rb")
>>> f
<_io.BufferedReader name='/music/_singles/kairo.mp3'>
>>> f.tell()
0
>>> f.seek(-128, 2)
7543421
>>> f.tell()
7543421
>>> tagData = f.read(128)
>>> tagData
b"TAGKAIRO****THE BEST GOA\x00\x00\x00\x00\x00\x00\x00\x00\x00***DJ MARY-JANE***\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Rave Mix\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x002000Kinsei's collection \x1f"
>>> f.tell()
7543549
>>>

A file object maintains state about the file it has open. The tell method of a file object tells you your
current position in the open file. Since you haven't done anything with this file yet, the current position is
0, which is the beginning of the file.

The seek method of a file object moves to another position in the open file. The second parameter
specifies what the first one means; 0 means move to an absolute position (counting from the start of the
file), 1 means move to a relative position (counting from the current position), and 2 means move to a
position relative to the end of the file. Since the MP3 tags you're looking for are stored at the end of the
file, you use 2 and tell the file object to move to a position 128 bytes from the end of the file.

The tell method confirms that the current file position has moved.

The read method reads a specified number of bytes from the open file and returns a string with the data
that was read. The optional parameter specifies the maximum number of bytes to read. If no parameter is
specified, read will read until the end of the file. (You could have simply said read() here, since you
know exactly where you are in the file and you are, in fact, reading the last 128 bytes.) The read data is
assigned to the tagData variable, and the current position is updated based on how many bytes were read.

The tell method confirms that the current position has moved. If you do the math, you'll see that after
reading 128 bytes, the position has been incremented by 128.

{source}
<!-- You can place html anywhere within the source tags -->
<pre class="brush:py;">

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f = open("/music/_singles/kairo.mp3", "rb")
>>> f
<_io.BufferedReader name='/music/_singles/kairo.mp3'>
>>> f.tell()
0
>>> f.seek(-128, 2)
7543421
>>> f.tell()
7543421
>>> tagData = f.read(128)
>>> tagData
b"TAGKAIRO****THE BEST GOA\x00\x00\x00\x00\x00\x00\x00\x00\x00***DJ MARY-JANE***\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Rave Mix\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x002000Kinsei's collection \x1f"
>>> f.tell()
7543549
>>>

</pre>

<script language="javascript" type="text/javascript">
    // You can place JavaScript like this

</script>
<?php
    // You can place PHP like this

?>
{/source}

Closing Files

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f = open("/music/_singles/kairo.mp3", "rb")
>>> f
<_io.BufferedReader name='/music/_singles/kairo.mp3'>
>>> f.closed
False
>>> f.close()
>>> f
<_io.BufferedReader name='/music/_singles/kairo.mp3'>
>>> f.closed
True
>>> f.seek(0)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
f.seek(0)
ValueError: seek of closed file
>>> f.tell()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
f.tell()
ValueError: I/O operation on closed file
>>> f.read()
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
f.read()
ValueError: read of closed file
>>> f.close()
>>>

The closed attribute of a file object indicates whether the object has a file open or not. In this case, the file is still open (closed is False).

To close a file, call the close method of the file object. This frees the lock (if any) that you were holding on the file, flushes buffered writes (if any) that the system hadn't gotten around to actually writing yet, and releases the system resources.

The closed attribute confirms that the file is closed.

Just because a file is closed doesn't mean that the file object ceases to exist. The variable f will continue to exist until it goes out of scope or gets manually deleted. However, none of the methods that manipulate an open file will work once the file has been closed; they all raise an exception.

Calling close on a file object whose file is already closed does not raise an exception; it fails silently.

{source}
<!-- You can place html anywhere within the source tags -->
<pre class="brush:py;">

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> f = open("/music/_singles/kairo.mp3", "rb")
>>> f
<_io.BufferedReader name='/music/_singles/kairo.mp3'>
>>> f.closed
False
>>> f.close()
>>> f
<_io.BufferedReader name='/music/_singles/kairo.mp3'>
>>> f.closed
True
>>> f.seek(0)
Traceback (most recent call last):
    File "<pyshell#6>", line 1, in <module>
    f.seek(0)
ValueError: seek of closed file
>>> f.tell()
Traceback (most recent call last):
    File "<pyshell#7>", line 1, in <module>
    f.tell()
ValueError: I/O operation on closed file
>>> f.read()
Traceback (most recent call last):
    File "<pyshell#8>", line 1, in <module>
    f.read()
ValueError: read of closed file
>>> f.close()
>>>

</pre>

<script language="javascript" type="text/javascript">
    // You can place JavaScript like this

</script>
<?php
    // You can place PHP like this

?>
{/source}