Read File in Python: All You Need to Know

The contiguous set of bytes in which the data can be stored and organized in a certain format is called a file.

What Are File Paths

The string representing the location of the file in a system is called a file path. A file path consists of three parts, they are:

  • Folder Path

The path to the location of the folder in the system is called the folder path. A backslash(\) separates the subsequent folders in the folder path with the Windows operating system and by a forward slash(/) with the Unix operating system.

  • File Name

The name of the file which is to be accessed.

  • Extension

The suffix at the end of the name of the file separated by a period (.) is called the extension of the file. The extension of the file indicates the type of file.

Importance of Files in Python

  • Files provide a means for storage and serve as a storage unit in a computer system.
  • The output of the program must persist even after the program ends. Files are used to save the output of the program.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

File Access Modes 

Accessing a file or opening a file is governed by certain operations called File Access Modes. File access modes specify what operations one may perform on an opened file. There are several file access modes in Python;

  • Read Only (‘r’):

The file can be accessed or opened in the read mode only.

  •  Read and Write (‘r+’):

The file can be accessed or opened in both the read and write modes.

  • Write Only (‘w’):

The file can be accessed, opened, or both, in the write mode only. It overwrites the data in the file if the file already exists, otherwise; it creates a new file for writing in this mode.

  •  Write and Read (‘w+’):

The file can be accessed or opened in both the read and write modes. The data in the file is overwritten if the file already exists.

  •  Append Only (‘a’):

The file can be accessed or opened in write mode. The data to be returned to the file is added at the end of the data existing in the file in this mode. A new file is created if the data to be written to the file does not exist.

  •   Append and Read (‘a+’):

The file can be accessed or opened in both write and read mode. The data to be returned to the file is added at the end of the data already existing in the file in this mode. A new file is created if the data to be written to the file does not exist.

Two Operations Can Be Performed on Accessing a File. They Are:

  • Opening a File:

You need to make use of the open() function to open a file in python.

The syntax to define the open() function is as follows:

File_object = open(r"path_to_the_file","Access_Mode")

where path_to_the_file is the location of the file in the system.

Access_Mode is the file access mode in which the file must be opened and

r is the character that prevents the characters in the path_to_the_file to be treated as special characters.

  • Closing a File:

We make use of the close() function to open a file.

The syntax to define close() function is as follows:

File_object.close()

Example 1:

Python program to demonstrate open() function and close() function in Python: 

#using open function to open a file in read mode

file_object = open(r'C:/Users/admin/Desktop/images/sports.mp4',"r")

print('The file is opened in read mode\n')

#using close() function to close the file

file_object.close()

The output of the above program is shown in the snapshot below:

ReadPythonEx_1 

Two Operations Can Be Performed on Modifying a File. They Are:

  •   Reading From a File:

The data in a file can be read by using three methods. They are:

Ø  read():

The read() function reads the bytes in the file in the form of a string. The number of bytes to be read from the file is specified as a parameter to the read() function, in case if the parameter is not specified, the read() function reads the entire file.

The syntax to define read() function is as follows:

File_object.read([n])

where n specifies the number of bytes to be read from the file. 

Ø  readline():

The readline() function reads a line in the file and returns it in the form of a string. The number of bytes to be read from the file is specified as a parameter to the readline() function but more than one line cannot be read using readline() function.

The syntax to define readline() function is as follows:

File_object.readline([n])

where n specifies the number of bytes to be read from the file. 

Ø  readlines():

The readlines() function reads all the lines from a file and returns each line as an element of type string in a list.

The syntax to define readlines() function is as follows:

File_object.readlines()

  • Writing to a File:

The data can be written to a file using two methods. They are:

Ø  write():

The write() function writes the data specified as a parameter to the write() function, to the file in a single line.

The syntax to define write() function is as follows:

File_object.write(data)

where data is the data to be written to the file in a single line. 

Ø  writelines():

The writelines() function is used to write a list of string elements to the file. Multiple string elements from the list can be written at once using the writelines() function.

The syntax to define writelines() function is as follows:

File_object.writelines(List])

where list represents a list of string elements, List = [string1, string2, string3]

FREE Data Science With Python Course

Start Learning Data Science with Python for FREEStart Learning
FREE Data Science With Python Course

Example 2:

Python program to demonstrate write() function, writelines() function, read() function, readline() function, and readlines() function in Python: 

#using open function to open a file in write mode

file_object = open(r'C:/Users/admin/Desktop/images/example.txt',"w")

#defining a list to be written to the file

list = ["Welcome \n", "to\n", "Simplilearn\n"]

#using write() function and writelines() function to write the data to the file

file_object.write('This is the first line in the file\n')

file_object.writelines(list)

#using close() function to close the file

file_object.close()

file_object1 = open(r'C:/Users/admin/Desktop/images/example.txt',"r")

print("Using read() function:\n")

#using read() function to read the entire data from the file

fileread =file_object1.read()

print(fileread)

#using seek() function to bring the file handler to the beginning of the file

file_object1.seek(0)

print("Using readline() function:\n")

#using readline() function to read the first 50 characters from the file

fileread1 = file_object1.readline(50)

print(fileread1)

file_object1.seek(0)

print("Using readlines() function:\n")

#using readlines() function to read the list from the file

fileread2 = file_object1.readlines()

print(fileread2)

 file_object1.close()

The output of the above program is shown in the snapshot below:

ReadPythonEx_2.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Conclusion

In this tutorial, you have learned the concept of ‘read file’ in Python. Simplilearn offers a Python Certification Course designed to help you learn everything you need to kick start your career in Python. And this is a very flexible way to gain skills in Python. Read our next tutorial on JSON Python.

Do you have questions for us regarding this tutorial? Please leave them in the comments section, and our experts will get back to you on the same, at the earliest. Happy learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.