Top 10 Programming Languages to Learn in 2019

PythonPython Basic Tutorial

File handling in Python

file handling in python

In Python, file handling requires no extra library to process files. Both text files and binary files can be operated in python. Unlike other programming languages file handling in python is pretty easy and can be implemented with minimum lines of code.

One thing worth noting is that python treats binary and text files differently and this should be kept in mind while working. Also, each file ends with an EOF indicator to tell the interpreter that the file has ended.

In this tutorial we will cover these topics on file handling:

File modes in python

CharacterMeaning
‘r’open for reading (default)
‘w’open for writing, truncating the file first
‘x’create a new file and open it for writing
‘a’open for writing, appending to the end of the file if it exists
‘b’binary mode
‘t’text mode (default)
‘+’open a disk file for updating (reading and writing)
‘U’universal newline mode (deprecated)

Points worth to note:

  • The default mode is ‘rt’ (open for reading text).
  • For binary random access, the mode ‘w+b’ opens and truncates the file to 0 bytes, while ‘r+b’ opens the file without truncation.
  • The ‘x’ mode implies ‘w’ and raises a FileExistsError if the file already exists.
  • Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn’t.
  • Files opened in binary mode (appending ‘b’ to the mode argument) return contents as bytes objects without any decoding.
  • In text mode (the default, or when ‘t’ is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
  • ‘U’ mode is deprecated and will raise an exception in future versions of Python. It has no effect in Python 3. Use newline to control universal newlines mode.

Create a file in Python

With Python you can create a .txt files (PyBlog.txt) by using the code, we have demonstrated here how you can do this .

We will be using in-built function open() to open the file in read and write mode. This function returns a file object. Let’s go through a step by step example to make you understand better.

Step – 1

file_new = open('pyblog.txt', mode='w+')
  • Now, as you can see that open(filename, mode) requires two basic arguments to work. Different types of mode to open a file has been discussed above.
  • ‘w+’ mode in argument suggests that we are opening our file in write plus mode. If the file doesn’t exist in the present directory of the file then it will be created.

Step – 2

for i in range(11):
    file_new.write('This is Line Number ' + str(i) + '\n')
  • Now that you have opened the file in write mode you can write in it. We will use the write() method of the file_new object to write into the file.
  • ‘\n’ last line returns the cursor in the new line. If you are new to escape characters then you should have a look at our Escape character tutorial to understand better.

Alternatively:

You can also use Python print() function to print on the file.

for i in range(11):
    print('This is Line Number ' + str(i), file=file_new)
  • Please note that you don’t require a ‘\n’ to return the cursor to the new line as the print() function automatically does that for you.
  • You will have to pass the file object name as the keyword argument.

Step – 3

file_new.close()
  • Finally you will have to close the file to store it in hard drive.

Output:

 This is Line Number 0
This is Line Number 1
This is Line Number 2
This is Line Number 3
This is Line Number 4
This is Line Number 5
This is Line Number 6
This is Line Number 7
This is Line Number 8
This is Line Number 9
This is Line Number 10

Append a file in python

To append a file in python you have open the file in ‘a’ mode, to be on a safe side you can also open the file in ‘a+’ mode so that it doesn’t throw an exception is the file does not exists.

Step – 1

file_new = open('pyblog.txt', mode='a+')
  • Like this previous example we have to first open the file, but this time in ‘a+’ mode.
  • We will be appending some info in the same file which we created in the previous example.

Step – 2

for i in range(11, 21):
    print('This is Line Number ' + str(i), file=file_new)
  • We ran a for loop from 11 to 20 and printed the string in the file
  • This will write the data in the append mode and any previous data will not be affected.
  • It is worth to note that the data is appended at the end of the file, but with some tweaking in the code we can also change the place where data should be appended.

Alternatively:

for i in range(11, 21):
    file_new.write('This is Line Number ' + str(i) + '\n')
  • You can also use the file write method, just make sure to append a new line escape character at the end.

Step – 3

file_new.close()
  • Finally you will have to close the file to store it in hard drive.

Output:

 This is Line Number 0
This is Line Number 1
This is Line Number 2
This is Line Number 3
This is Line Number 4
This is Line Number 5
This is Line Number 6
This is Line Number 7
This is Line Number 8
This is Line Number 9
This is Line Number 10 // the file has been appended
This is Line Number 11
This is Line Number 12
This is Line Number 13
This is Line Number 14
This is Line Number 15
This is Line Number 16
This is Line Number 17
This is Line Number 18
This is Line Number 19
This is Line Number 20

Read a file in Python

By default the open() function uses the ‘r’ or read mode. (Just open it to read it :D)

Step – 1

file_new = open('pyblog.txt')
  • Open the file in read mode.
  • Check if it is read mode before doing further operation. Trust it will save you in many pesky situations. 😉

Step – 2

if file_new.mode == 'r':
    for i in file_new:
        print(i, end='')

Alternatively:

Use the read() method to read the file.

if file_new.mode == 'r':
    c = file_new.read()
    for i in c:
        print(i, end='')

Step – 3

file_new.close()
  • Close the file
 This is Line Number 0
This is Line Number 1
This is Line Number 2
This is Line Number 3
This is Line Number 4
This is Line Number 5
This is Line Number 6
This is Line Number 7
This is Line Number 8
This is Line Number 9
This is Line Number 10
This is Line Number 11
This is Line Number 12
This is Line Number 13
This is Line Number 14
This is Line Number 15
This is Line Number 16
This is Line Number 17
This is Line Number 18
This is Line Number 19
This is Line Number 20

Summary

  • Python allows you to read, write and delete files
  • Use the function open(“filename.txt”,”w+”) to create a file. The + tells the python compiler to create a file if it does not exist
  • To append data to an existing file use the command open(“filename.dat”, “a”)
  • Use the read() method to read the ENTIRE contents of a file
  • Use the readlines() method to read the content of the file one by one.

Related posts
ProgrammingPythonPython Basic Tutorial

Mastering Print Formatting in Python: A Comprehensive Guide

ProgrammingPython

Global Variables in Python: Understanding Usage and Best Practices

ProgrammingPythonPython Basic Tutorial

Secure Your Documents: Encrypting PDF Files Using Python

ProgrammingPython

Creating and Modifying PDF Files in Python: A Comprehensive Guide with Code Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.