Files

Python uses file objects to interact with external files on your computer. These file objects can be any sort of file you have on your computer, whether it be an audio file, a text file, emails, Excel documents, etc. Note: You will probably need to install certain libraries or modules to interact with those various file types, but they are easily available.

Inorder to work with files we must have oone, go ahead and create a sample text (.txt) file in this notebook directory.

If you dont know the directory of your current note book, type pwd in your notebook and you will know.


In [1]:
pwd


Out[1]:
'D:\\Python\\PracticeNotebooks'

So the above is the path where you have to create the text file, in order to use it in this notebook. I have created mine as test.txt

Python has a built-in open() function that allows us to open and play with basic file types.


In [4]:
f = open('test.txt')

Reading Files

Now we have opened our text file, and the object f is the reference for that file. What we can try now is to print the contents of that file using builtin read() function for files.


In [5]:
f.read()


Out[5]:
'This is a sample text file.\nThis is a sample line in this text file.'

The above is the content in our file. Notice that the new line will be treated as \n. But when we call read() again it will not print anything.


In [6]:
f.read()


Out[6]:
''

This is because python uses a cursor to read data from the file. After you called the read() for the first time, the cursor would read all the content in the file and will be at the end of the file, so when you call read() again there is nothing to be read.

We can reset the cursor using the seek() function. (0 has to be passed to seek() inorder to reset the cursor to the starting of the file)


In [9]:
f.seek(0)


Out[9]:
0

In [8]:
f.read()


Out[8]:
'This is a sample text file.\nThis is a sample line in this text file.'

In order to not have to reset every time, we can also use the readlines() method. Use caution with large files, since everything will be held in memory.


In [10]:
f.readlines()


Out[10]:
['This is a sample text file.\n', 'This is a sample line in this text file.']

Writing to files

By default the open function opens the file in read mode, in order to write to the file we must open the file in write mode.

To open a file in write mode, pass a second parameter to the open() function. The parameter value is 'w+'.


In [12]:
# opening the file in wirte mode
f = open('test.txt', 'w+')

In [13]:
# Writing to the file using write() function
f.write('This the text line inserted through python')


Out[13]:
42

In [15]:
# Placing the cursor at the starting of the file.
f.seek(0)


Out[15]:
0

In [16]:
# Reading the contents of the file.
f.read()


Out[16]:
'This the text line inserted through python'

Notice that the previous content in the file is been overwritted.

Appending content to the file.

To appen new content to the existing file contents we must open the file in append (a) mode.


In [17]:
f = open('test.txt', 'a')

In [19]:
f.write('This is the appended line from python ')


Out[19]:
38

Remember that we have opened the file in append mode, so reading is not allowed.


In [20]:
f.read()


---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-20-bacd0e0f09a3> in <module>()
----> 1 f.read()

UnsupportedOperation: not readable

After using the file it is recomended that you close it using close() function.


In [21]:
f.close()

Now we will open it again in read mode. The default mode is read mode.


In [22]:
f = open('test.txt')

In [23]:
f.read()


Out[23]:
'This the text line inserted through pythonThis is the appended line from python '

Iterating through a file

We can use a for loop to iterate through a file and print its content without using read(). This will save memory as we are not storing anything.

First lets create another file from this notebook using IPython Magic:


In [24]:
%%writefile new.txt
First line of text
Second line of text


Writing new.txt

As our file is created, now lets print its content using for.


In [25]:
for line in open('new.txt'):
    print(line)


First line of text

Second line of text

As you can see we have not used read(). The for loop above will iterate through every line of content in the file and prints it using print(). line here is just an instance in for loop.