Python File Handling

The random access memory is volatile, and all its contents are lost once a program terminates.

In order to persist the data forever, we use files.

A file is data stored in a storage device. A python program can talk to the file by reading content from it and writing content to it.

Variables provide us a way to store data while the program runs, if we want out data to persist even after the termination of the program, we have to save it to a file.

Python_File_Handling

Types of Files

There are 2 types of files:

  1. Text files (.txt, .c, etc)
  2. Binary files (.jpg, .dat, etc)

Python has a lot of functions for reading, updating, and deleting files.

Opening a file

Python has an open() function for opening files. It takes 2 parameters: filename and mode.

open(“this.txt”, “r”)

Here, “this” is the file name and “r” is the mode of opening (read mode)

Reading a file in Python

f = open(“this.txt”, “r”)     #Opens the file in r mode

text = f.read()          #Read its content

print(text)     #Print its contents

f.close()         #Close the fie

We can also specify the number of characters in read() function:

f.read(2)       #Reads first 2 characters

Other methods to read the file

We can also use f.readline() function to read one full line at a time.

f.readline()               #Reads one line from the file

Modes of opening a file

r – open for reading

w – open for writing

a – open for appending

+ -> open for updating

‘rb’ will open for read in binary mode

‘rt’ will open for read in text mode

Writing Files in Python

In order to write to a file, we first open it in write or append mode, after which, we use the python’s f.write() method to write to the file!

f = open(“this.txt”, “w”)

f.write(“This is nice”)        #Can be called multiple times

f.close()

With statement

The best way to open and close the file automatically is the “with” statement.

with open(“this.txt”) as f:

            f.read()

#There is no need to write f.close() as it is done automatically

Exercise on Python File Handling

  1. Write a program to read the text from a given file, “poems.txt” and find out whether it contains the word ‘twinkle’.
  2. The game() function in a program lets a user play a game and returns the score as an integer. You need to read a file “Hiscore.txt” which is either blank or contains the previous Hi-score. You need to write a program to update the Hi-score whenever game() breaks the Hi-Score.
  3. Write a program to generate multiplication tables from 2 to 20 and write it to the different files. Place these files in a folder for a 13- year old boy.
  4. A file contains the word “Donkey” multiple times. You need to write a program which replaces this word with ###### by updating the same file.
  5. Repeat program 4 for a list of such words to be censored.
  6. Write a program to mine a log file and find out whether it contains ‘python’.
  7. Write a program to find out the line number where python is present from question 6.
  8. Write a program to make a copy of a text file “this.txt.”
  9. Write a program to find out whether a file is identical and matches the content of another file.
  10. Write a program to wipe out the contents of a file using python.
  11. Write a python program to rename a file to “renamed_by_python.txt.”
Was this article helpful?
YesNo

Leave a Comment

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