Introduction

Python has in-built support for file handling. It allows users to handle files i.e. to read and write files, along with many other file handling options, to operate on files. There are always two parts of a file in the computer system, the filename and its extension. Also, the files have two key properties – its name and the location or path, which specifies the location where the file exists.

Since, random access memory (RAM) is volatile which loses its data when computer is turned off. So files are used to save data for future use. When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.

Open a File

open() function is used to open a file. Its syntax is

file_object = open(filename [,mode] [,buffering])

where

  • filename: Name of the file.
  • mode: Which mode the file has to be open.
  • buffering: If the value set to zero (0), no buffering will occur while accessing a file. If the value is set to top one (1), line buffering will be performed while accessing a file.

A file can be opened in the following modes:

  • r : Opens a file for reading only. (It’s a default mode.)
  • w : Opens a file for writing. (If a file doesn’t exist already, then it creates a new file. Otherwise, it’s truncate a file.)
  • x : Opens a file for exclusive creation. (Operation fails if a file does not exist in the location.)
  • a : Opens a file for appending at the end of the file without truncating it. (Creates a new file if it does not exist in the location.)
  • t : Opens a file in text mode. (It’s a default mode.)
  • b : Opens a file in binary mode.
  • + : Opens a file for updating (reading and writing.)

If an attempt to open a file fails then open returns a false value, otherwise it returns a file object that provides various information related to that file.

#1 File opening
fo = open("sample.txt", "wb")
print ("Name: ", fo.name)
print ("Mode: ", fo.mode)
print ("Is Closed: ", fo.closed)
print ("Softspace flag : ", fo.softspace)

# Output
# Name: sample.txt
# Mode: wb
# Is Closed: False
# Softspace flag: 0

# Create a file in text mode
fo = open("test.txt",'w')

# Read and write in binary mode
fo = open("img.bmp",'r+b')

# Specify the encoding type
fo = open("test.txt",mode = 'r',encoding = 'utf-8')

Read from File

There is more than one way to read a file. The read functions contains different methods, read(),readline() and readlines()

file = open("file.txt", "r") 

# Read all characters in the file
print(file.read())

# Read the first five characters of stored data and return it as a string
print(file.read(5))

# Read single line of information from the file
print(file.readline()) 

# Read third line in the file 
print (file.readline(3))

# Read all the line in the file 
print(file.readlines())

# Bring file cursor to initial position
file.seek(0)

# Get the current file position
file.tell()

# Iterate over the lines of the File
with open('filename.txt') as f:
for line in f :
   print(line, end=' ')

Write to File

Method to writes a sequence of strings to the file are write(), writelines(). In order to write into a file, we need to open it in write ‘w’, append ‘a’ or exclusive creation ‘x’ mode.

file = open(“demo.txt”, “w”)
 
file.write(“This is a test”) 
file.write(“To add more lines.”)

# write() method returns the number of characters written to the file.
# This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is overwritten.
with open("test.txt",'w',encoding = 'utf-8') as f:
  f.write("my first file\n")
  f.write("This file\n\n")
  f.write("contains three lines\n")

Close a File

When we are done with operations to the file, we need to properly close the file to free up the resources tied with the file.

f = open("test.txt",encoding = 'utf-8')

#1 Close file
f.close()

# 2 Safer way to close file
try:
  f = open("test.txt",encoding = 'utf-8')
  # perform file operations
finally:
  f.close()

The best way to do this is using the with statement. This ensures that the file is closed when the block inside with is exited. We don’t need to explicitly call the close() method. It is done internally.

with open("test.txt",encoding = 'utf-8') as f:
  # perform file operations