File Handling in Python

Table of Contents

File Handling

There are three steps to reading or writing files in Python.

  1. Call the open() function to return a File object.
  2. Call the read() or write() method on the File object.
  3. Close the file by calling the close() method on the File object.

Opening a file

You can open a file in python by ‘open’ function. open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

Syntax

f = open('workfile.txt', 'w')

Closing a file

You should always close a file after doing stuffs. For this you can use close() function.

Syntax

file.close()

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks.

with open("workfile.txt") as f:
    for line in f:
        print(line)

# After printing the lines the file will be closed.

If mode field is empty, it will open the file in ‘r’ read mode.

Reading a Text File

read() function

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). Size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned.

Example

#“workfile.txt” contains following lines
#This is first line
#This is second line
#This is third line

with open("workfile.txt", "r") as f:
  data = f.read()
  print(data)

Out put

This is first line
This is second line
This is third line

readline() function

f.readline() reads a single line from the file.

Example

with open("workfile.txt", "r") as f:
  data = f.readline()
  print(data)

Out put

This is first line

readlines() function

The readlines() method to get a list of string values from the file, one string for each line of text.

Example:

with open("workfile.txt", "r") as f:
  data = f.readlines()
  print(data)

Output

['This is first line\n', 'This is second line\n', 'This is third line\n']

Create a text file

Python allows you to write content to a file. You can’t write to a file you’ve opened in read mode, though. Instead, you need to open it in “write plaintext” mode or “append plaintext” mode, or write mode and append mode for short. Write mode will overwrite the existing file and start from scratch. Pass 'w' as the second argument to open() to open the file in write mode. Append mode, on the other hand, will append text to the end of the existing file. If the filename passed to open() does not exist, both write and append mode will create a new, blank file.

Example:

f.write(string) writes the contents of string to the file, returning the number of characters written
f = open('workfile.txt', 'w')
f.write('This is a test\n')
f.write('Hi User!\n')
f.write('Welcome to Python Easy!\n')
f.close()
f = open('workfile.txt')
content = f.read()
f.close()
print(content)

Output

This is a test
Hi User!
Welcome to Python Easy!
Click any Link
to navigate to certain page easily
Write a line to us
Your Email
Title
Description