Python Basic Tutorial

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.

Related Post
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.

K

Share
Tags: Programming Python Python Basic Tutorial

Recent Posts

  • Programming

Mastering Print Formatting in Python: A Comprehensive Guide

In Python, the print() function is a fundamental tool for displaying output. While printing simple…

8 months ago
  • Programming

Global Variables in Python: Understanding Usage and Best Practices

Python is a versatile programming language known for its simplicity and flexibility. When working on…

8 months ago
  • Programming

Secure Your Documents: Encrypting PDF Files Using Python

PDF (Portable Document Format) files are commonly used for sharing documents due to their consistent…

8 months ago
  • Programming

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

PDF (Portable Document Format) files are widely used for document exchange due to their consistent…

8 months ago
  • Programming

Boosting Python Performance with Cython: Optimizing Prime Number Detection

Python is a high-level programming language known for its simplicity and ease of use. However,…

8 months ago
  • Programming

Using OOP, Iterator, Generator, and Closure in Python to implement common design patterns

Object-Oriented Programming (OOP), iterators, generators, and closures are powerful concepts in Python that can be…

8 months ago

This website uses cookies.