Python File I/O | How to read write files in Python

FREE Online Courses: Click for Success, Learn for Free - Start Now!

Python offers some excellent ways of using files. In python, there are multiple functions to read data from a file and write data to a file. These functions allow us to work with files efficiently. In this article, we will learn about all those functions and how to use them. First, let us start with the modules that we need to use those functions.

Module

All common operations that are required to work with files are readily available in the builtins module. Hence we don’t need to import any module, unlike other programming languages.

Order of Working with Python Files

When working with files, we usually follow the following order:

  • Opening the file – We first open the file that we need to perform any operations on it.
  • Performing operation on the file – We perform the required operations, like reading or writing, on the opened file.
  • Closing the file – Finally, after performing all operations, we close the file.

How to Open a file in Python

We first need to open the required file before we perform any operation on it. We can use the built-in function open() with the following syntax to open a file.

Syntax

open(file, mode)

It has the following parameters:

  • file . A string containing the filename of the file we wish to open.
  • mode – A string representing the mode of opening the file.

We can pass the following values for the parameter mode:

Value for mode Description
‘r’ For reading from the file
‘w’ For writing to the file
‘x’ For exclusive creating a new file
‘a’ For appending to the file
‘t’ For opening the file in text mode
‘b’ For opening the file in binary mode
‘+’ For updating the file

The function returns a file object which can be used to perform different operations on the file. The file object is also called a handle. It raises a FileNotFoundError if the passed file is not found.

Example of opening a file in Python

file = "PythonGeeks.txt"

f = open(file, 'r')
print("The file is opened")

Output

The file is opened

How to close a file in Python

After using the file, we must close it to flush any unwritten information. To do this, we can use the built-in function close() with the following syntax:

Syntax

file.close()

It has no parameters and no return value.

Using the function ensures that all the resources linked to the file are freed.

Example of closing a file

file = "PythonGeeks.txt"

f = open(file, 'r')
f.close()
print("The file is closed")

Output

The file is closed

Try…Finally in Python

While running the program, any errors between the open() and close() functions will result in a program termination without properly closing the file.

Example of program termination without closing the file

file = "PythonGeeks.txt"

f = open(file, 'r')

num = int("World")

f.close()
print("The file is closed")

Output

ValueError: invalid literal for int() with base 10: ‘World’

In the above code example, the program got terminated before running the close function. Hence the file is not properly closed.

To keep this from happening, we can use the try…finally statements. These statements ensure that the file is closed before the program termination even if there are any errors in the program.

Example of using try…finally statement in Python

file = "PythonGeeks.txt"

try:
   f = open(file, 'r')
   num = int("World")
finally:
   f.close()
   print("The file is closed")

Output

The file is closed

Although this does handle the exceptions pretty well, there is a more optimal way of working with files.

With keyword in python

Using the with keyword is better and more optimal than using try…finally statements. It is only available from Python 2.5 versions.

Example of using with keyword in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print("File opened")

print("File closed")

Output

File opened
File closed

In the above code example, the file gets closed as soon as the program exits the indentation of the with statement.

How to Read a File in Python

To read a file in Python, we need to open it in the read ‘r’ mode. Then we can use any of the following functions to read data from the file.

read()

To read a file, we use the following syntax.

Syntax

read(size)

It has the following parameter.

  • Size – Number of bytes we want to read in the file

The default value of size is -1.

If no argument is passed, then it chooses the default value and returns the entire file.

It returns the passed number of bytes of data from the file.

Example of using read() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.read(6))  # to read only six bytes

Output

Python

Example of using read() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.read()) # to read the entire file

Output

PythonGeeks1
PythonGeeks2
PythonGeeks3

readline()

The function is used to read a file line by line. It reads a line until it encounters the newline character. We don’t need to pass any arguments. It returns a line in the file until the newline character.

Example of using readline() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.readline())

Output

PythonGeeks1

readlines()

It is similar to the previously discussed function readline() in Python but instead of reading and returning line by line, it reads all lines in a file and returns the list of lines in that file. No arguments are needed for this function.

Example of using readlines() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.readlines())

Output

[‘PythonGeeks1\n’, ‘PythonGeeks2\n’, ‘PythonGeeks3’]

How to Write a File in Python

To write a file in python, we need to open it in write ‘w’ mode. Then we can use any of the following functions to write data to the file.

write()

The function is used to write content in a file. We need to pass the string that we want to write in the file and the function writes the passed string in that file. It returns the number of bytes of data it has written in that file. We can only write strings to a file.

Example of using write() in Python

file = "PythonGeeks.txt"

with open(file, 'w') as f:
   print(f.write("Learn Python"))

Output

12

writelines()

The function is used to write multiple lines at once in a file. We need to pass a list of lines that we want to write in a file. Each line in the list should end with a newline character. It has no return value.

Example of using writelines() in Python

file = "PythonGeeks.txt"

lines = ["Learn Python\n", "Learn Computer\n", "Learn using PythonGeeks\n"]

with open(file, 'w') as f:
   print(f.writelines(lines))

Output

None

If the file we opened already exists and contains some data, then following the above methods to write to a file will replace the existing content in that file.

To avoid this, Python provides us another way to write new content without replacing the existing content. This is called appending a file.

Append a File in Python

To append content to a file, we need to open it in append ‘a’ mode. This enables us to add content to a file without replacing the old content. After opening the file in append mode, we can use either write() or writelines() function to add content to the file.

Example of appending a file in Python

file = "PythonGeeks.txt"

with open(file, 'a') as f:
   print(f.write("New Content"))

Output

11

Accessing the Pointer Position in Python

Every time we perform a read or write or append operation, the pointer changes its position. To get the exact position of the pointer, we use the function tell().

  • It has no parameters.
  • It returns the current position of the pointer.

Example of using tell() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   f.read(4)
   print(f.tell())

Output

4

Modifying the Pointer Position in Python

We use the function seek() to change the position of the pointer. The function has no return value and has the following syntax.

Syntax

file.seek(offset, from_what)

It has the following two parameters:

  • offset – It is the number of positions to move
  • from _what – It sets the reference point for the offset.

We can pass the following values for the parameter from_what:

Value for from_what Description
0 To set the reference point at the start of the file
1 To set the reference point at the current pointer position
2 To set the reference point at the end of the file

The default value of from_what is 0.

Example of using seek() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   f.read(4)
   print(f.tell())
   f.seek(1) # Position changed to index 1
   print(f.read(10))

Output

4
ythonGeeks

Methods of Python File Object

flush()

It is similar to fflush() function in the C language. The function is used to flush the internal buffer. It has no return value.

Example of using fflush() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.flush())

Output

None

fileno()

The underlying implementation uses an integer file descriptor to request I/O operations from the operating system. We use the function fileno() to get that integer.

Example of using fileno() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.fileno())

Output

3

isatty()

The function is used to check whether the file is connected to a tty device or not. It returns True if it is connected or False if it is not connected.

Example of using isatty() in Python

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.isatty())

Output

False

truncate(size)

The function is used to change the size of a file. We need to pass the required file size in bytes and the size of the file will be changed to the passed size. It returns the passed size.

Example of using truncate() in Python

file = "PythonGeeks.txt"

with open(file, 'w') as f:
   print(f.truncate(777))

Output

777

Delete File in Python

We use the function remove() from the os module to delete a file. We need to pass a string containing the name of the file that we want to delete. It has no return value. It raises FileNotFoundError if the passed file is not found.

Example of using remove() in Python

import os

file = "PythonGeeks.txt"

os.remove(file)
print(f"{file} is deleted")

Output

PythonGeeks.txt is deleted

More About Files

Python contains a large number of functions to make working with files easier. To learn more about those functions, see the following articles:

  • Python Directory: Many of the functions for working with directories are covered in this article.
  • Python OS Module: All the functions accessible in the os module are listed in this article.

Python Interview Questions on File I/O

Q1. Write a program to print the first 11 characters of the file PythonGeeks.txt.

Ans 1. Complete code is as follows:

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.read(11))  # print first 11 characters

Output

PythonGeeks

Q2. Write a program to print the first 3 lines of the file PythonGeeks.txt without using a loop.

Ans 2. Complete code is as follows:

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   print(f.readlines()[:3]) # print first 3 lines

Output

[‘PythonGeeks1\n’, ‘PythonGeeks2\n’, ‘PythonGeeks3\n’]

Q3. Write a program to write the string “Hello World!” to the file PythonGeeks.txt.

Ans 3. Complete code is as follows:

file = "PythonGeeks.txt"

with open(file, 'w') as f:
   print(f.write("Hello World!"))

Output

12

Q4. Write a program to write the given lines to the file PythonGeeks.txt without replacing the existing content.
Lines:
Line 1 – Save Energy
Line 2 – Save Earth
Line 3 – Save Life

Ans 4. Complete code is as follows:

file = "PythonGeeks.txt"

lines = ["Save Energy\n", "Save Earth\n", "Save Life\n"]
with open(file, 'a') as f:
   print(f.writelines(lines))

Output

None

Q5. Write a program to print the fifth character of the file PythonGeeks.txt.

Ans 5. Complete code is as follows:

file = "PythonGeeks.txt"

with open(file, 'r') as f:
   f.seek(4)
   print(f.read(1))

Output

o

Quiz on Python Files I/O

Conclusion

In this article, we learned about the various ways of reading and writing files. We discussed the multiple functions that we can use to read and write a file. We also learned how to access and modify the pointer position of a file. Furthermore, if you have any feedback, please do not hesitate to share them in the comments section.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


Leave a Reply

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