How to read from a file in Python

How to read from a file in Python

In this tutorial,we will learn how to read from a file with some easy examples. python  can  handle two types of files i.e normal text files and binary files (written in binary language, 0s and 1s).

  • Text files: In this file, Each line of text is terminated with a special character called End of Line(‘\n’) in python by default.
  • Binary files: In this type of file, there is no terminator for a line and after converting it into machine-understandable binary language the data is stored .

Reading from a file in python

Inorder to read from a file first we need to open a file by  using the open() function. No module is required to be imported for this function.

syntax:
File_object = open("File_Name", "Access_Mode")
f = open("myfile.txt", "r")
print(f.read())
f.close()

here I created text file i.e my file. By using open function I opened the file with the read only mode.
The read() method:This function returns the bytes read as a string. If no n is specified, it then reads the entire file.

output:

Hello! Welcome to myfile.txt
This file is for testing purposes.
Good Luck!

file2=open("myfile.txt", "r")
print(file2.readline())
file2.close()

The readline() method:This function reads a line from a file and returns it as a string. it does not read more than one line.The close() function at the end it is used to close the file when you are done modifying it.

output:

Hello! Welcome to myfile.txt

 

access mode:

It defines  how the file will be used once it’s opened. it also defines from where the data has to be read or written in the file. There are Different access modes for reading a file are –

  1. Read Only (‘r’) : Open text file for only reading. it is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode.
  2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.

Leave a Comment

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

Scroll to Top