Files in Python

Files in Python with Examples

In this article, I am going to discuss Files in Python with examples. Please read our previous article where we discussed Custom Exception in Python. As part of this article, we are going to discuss the following pointers in details which are related to files in Python.

  1. What is a File?
  2. Types of Files
  3. File Modes
  4. Opening and Closing a File in Python
  5. Properties of File Object in Python
  6. Writing data to a File in Python
  7. Appending Content
  8. Reading data From a File in Python
  9. With Keyword in Python
  10. Seek and Tell Methods in Python
  11. Checking for the existence of a file in Python
  12. Program to print the number of lines, words and characters present in the given file
What is a File?

A file is a resource to store data. As part of the programming requirement, we may have to store our data permanently for future purpose. For this requirement we should go for files. Files are very common permanent storage areas to store our data.

Types of Files:

There can be two types of files based on the type of information they store. They are:

  1. Text files
  2. Binary files

Text files: Text files are those which store data in the form of characters or strings.

Binary files: Binary files are those which store entire data in the form of bytes, i.e a group of 8 bits each. While retrieving data from the binary file, the programmer can retrieve it in the form of bytes. Binary files can be used to store text, images, audio and video.

File Modes:

Before going into details of how to do operation on files in python, let’s understand about some modes which are required to work with them.

File Modes in Python

Note: All the modes in the table are applicable for text files. For binary files, the above modes need to be suffixed with ‘b’. For example, rb, wb, ab, r+b, w+b, a+b, xb.

Opening a File in Python:

Before performing any operation (like read or write or append) on the file, first we must open that file programmatically. In order to open the file, we have a predefined function open()in python. At the time of opening a file, we must specify the mode(one mode from the above table), which represents the purpose of opening a file.

Syntax: f = open(filename, mode)

When we execute the above command with proper filename and mode, then a file object will be returned, which we are storing in variable ‘f’. Operation performed on file object is the operation performed on file.

Closing a File in Python:

After completing our operations on the file, it is highly recommended to close the file programmatically. For this we have a predefined function close().

Syntax: f.close()

Properties of File Object in Python:

The file object which we get when we open a file has many predefined methods which can be called to get the information about the file and the mode.

  1. f.name → Name of opened file mode
  2. f.mode → Mode in which the file is opened
  3. f.closed → Returns a boolean value whether the file is closed or not
  4. f.readable() → Returns a boolean value whether the file is readable or not
  5. f.writable() → Returns a boolean value whether the file is writable or not
Program: Opening and closing a file in Python (demo1.py)
f=open("abc.txt", 'w')
print("File Name: ", f.name)
print("File Mode: ", f.mode)
print("Is File Readable: ", f.readable())
print("Is File Writable: ", f.writable())
print("Is File Closed : ", f.closed)
f.close()
print("Is File Closed : ", f.closed)

Output:

Opening and closing a file in Python

An empty file created with the name of abc.txt will be created in current directory after executing the above code.

Writing data to a File in Python:

We can write character data to the text files by using the following 2 methods:

  1. write(str)
  2. writelines(str)
Program: Writing data into file in python (demo2.py)
f=open("wish.txt", 'w')
f.write("Welcome\n")
f.write("to\n")
f.write("python world\n")
print("Data written to the file successfully")
f.close()

Output: Writing data into file in python

File Content: wish.txt

Welcome
to
python world
Appending Content

In the above program, data present in the file will be overridden every time if we run the program. Instead of overriding, if we want append the data then we should open the file in append mode as follows:

Syntax: f = open(“wish.txt”, “a”)

Program: Appending content (demo3.py)

f=open("wish.txt", 'a')
f.write("Welcome\n")
f.write("to\n")
f.write("python world\n")
print("Data written to the file successfully")
f.close()

Output: Appending content

File Content: wish.txt

Welcome
to
python world
Welcome
to
python world

While writing data using the write() method, the data will be written in a single line(demo3.py). If we want the data in different lines (demo4.py) then we need to use a separator(\n).

Program: Appending content in new line (demo4.py)
f=open("wish.txt", 'a')
f.write("Welcome ")
f.write("to ")
f.write("python world")
print("Data written to the file successfully")
f.close()

Output: Appending content in new line

File Content: wish.txt

Welcome
to
python world
Welcome
to
python world
Welcome to python world
Writelines(argument) method in python:

We can write lines of text into the file by using writelines method

Program: writelines method (demo5.py)

f=open("names.txt", 'w')
list=["Ramesh\n" ,"Arjun\n", "Senthil\n", "Vignesh"]
f.writelines(list)
print("List of lines written to the file successfully")
f.close()

Output: Writelines(argument) method in python

File names.txt:

Ramesh
Arjun
Senthil
Vignesh
Reading data From a File in Python:

We can read character data from text file by using the following read methods:

  1. read() → To read total data from the file.
  2. read(n) → To read ‘n’ characters from the file.
  3. readline() → To read only one line.
  4. readlines() → To read all lines into a list.

File abc.txt content

Hello everyone!!
This topic is very important
Please don't sleep
Once this topic done
Then happily you can sleep
Thanks for cooperating
Program: read() method (demo6.py)
f=open("abc.txt", 'r')
data=f.read()
print(data)
f.close()

Output:

Reading data From a File in Python using read method

Program: read(n) method (demo7.py)
f=open("abc.txt", 'r')
data=f.read(20)
print(data)
f.close()

Output:

Reading data From a File in Python using read(n) method

Readline() method in Python:

By using readline() we can read line by line from file

Program: readline() method (demo8.py)

f=open("abc.txt", 'r')
line1=f.readline()
print(line1, end='')
line2=f.readline()
print(line2, end='')
line3=f.readline()
print(line3, end='')
f.close()

Output:

Reading data From a File in Python using readline method

Readlines() method in python:

By using readlines() method we can read all lines

Program: readlines() method (demo9.py)

f=open("abc.txt", 'r')
lines=f.readlines()
for line in lines:
   print(line, end='')
f.close()

Output:

Reading data From a File in Python using readlines method

With Keyword in Python:

with is a keyword in python. This keyword can be used while opening a file. We can use this to group file operation statements within a block.

Advantage of with Keyword:

Earlier, we discussed that, when we open a file programatically, it needs to closed after doing the operations. The advantage of this ‘with’ keyword is that it will take care of closing the file. After completing all operations automatically even in the case of exceptions also, and we are not required to close explicitly.

Program: with keyword in python (demo10.py)

with open("test.txt", "w") as f:
   f.write("Welcome\n")
   f.write("to\n")
   f.write("Python\n")
   print("Is File Closed: ", f.closed)
print("Is File Closed: ", f.closed)

Output:

with keyword in python

File: test.txt

Welcome
to
Python
Seek and Tell Methods in Python:
tell() method:

We can use the tell() method to return the current position of the cursor(file pointer) from the beginning of the file. The position(index) of the first character in files starts from zero just like string index.

File: test.txt

Welcome
to
Python
Program: tell method in Python (demo11.py)
f=open("test.txt", "r")
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())

Output:

tell method in Python

Seek() method in python:

We can use seek() method to move cursor(file pointer) to specified location. For this method we need to provide two arguments: offset, fromwhere. The second argument is optional.

Syntax: f.seek(offset, fromwhere)

Here, offset represents the number of positions and The allowed values for second arguments are:

  1. 0 —> From beginning of file (default value)
  2. 1—->From current position
  3. 2 —> From end of the file
Program: seek method (demo12.py)
data="SampurneshBabu movie is excellent"
f=open("abc.txt", "w")
f.write(data)
with open("abc.txt", "r+") as f:
   text=f.read()
   print(text)
   print("The Current Cursor Position: ",f.tell())
   f.seek(24)
   print("The Current Cursor Position: ",f.tell())
   f.write("Britania Bisket")
   f.seek(0)
   text=f.read()
   print("Data After Modification:")
   print(text)

Output:

Seek() method in python

Checking for the existence of a file in Python:

In python, we have a module named ‘os’ which can be used to get information about files in our computer. The ‘os’ module has submodule ‘path’, which contains isfile() function to check whether a particular file exists or not

Syntax: os.path.isfile(fname)

Program: Checking for the existence of a file in Python (demo13.py)

import os, sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
   print("File exists:", fname)
   f=open(fname, "r")
else:
   print("File does not exist:", fname)
   sys.exit(0)
print("The content of file is:")
data=f.read()
print(data)

Output:

Checking for the existence of a file in Python

sys.exit(0)

sys.exit(0) can be used to exit the system without executing the rest of the program. The argument represents status code and 0 means normal termination and it is the default value.

Program to print the number of lines, words and characters present in the given file
import os, sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
   print("File exists:", fname)
   f=open(fname, "r")
else:
   print("File does not exist:", fname)
   sys.exit(0)
lcount=wcount=ccount=0
for line in f:
   lcount=lcount+1
   ccount=ccount+len(line)
   words=line.split()
   wcount=wcount+len(words)
print("The number of Lines:", lcount)
print("The number of Words:", wcount)
print("The number of Characters:", ccount)

 

Output:

Program to print the number of lines, words and characters present in the given file

In the next article, I am going to discuss Working with Binary Files in Python with Examples. Here, in this article, I try to explain Files in Python with Examples. I hope you enjoy this Files in Python article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.