How to read from a file in python

Python provides  functions for creating, writing and reading files. There are 2 types of files that can be handled in python, 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 EOL(End of line), which is new line character(‘\n’) in python by default

Binary files: In this type of file, there is no terminator for a line and data is stored after converting it into machine understandable binary language

Access mode

Access modes govern the type of operations possible in opened file. It refers to how the file will be used once its opened .Different access modes for reading a file are:

  • Read Only(“r”)
  • Read and Write(“r+”)
  • Append and Read(“a+”)

                                                                                                                                                                                                                                                          Opening a file

It is done using open() function. No module is required to be imported for this function

Syntax : File_object =  open(r”File_Name”,  “Access_Mode”)

file1 = open("MyFile.txt", "r")
file2 = open(r" D:\Text\MyFile2.txt", "r+")

Closing  a  file

close() function closes file and frees the memory space acquired by that file. It is used at time when file is no longer needed or it is to be opened in a different file mode

file1 = open("MyFile.text", "r")
file1.cilose()

Reading from a file

There are 3 ways to read data from a text file:

  • read(): Returns the read bytes in form of a string
  • readline(): Reads a line of file and returns in form of string
  • readlines(): Reads all the lines and return them as each line a string element in a list
    file1 = open("myfile.txt", "w")
    L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
    file1.write("Hello \n")
    file1.writelines(L)
    file1.close()
    file1 = open(my file .text",  "r+")
    print("Output of Read function is ")
    print(file1.read())
    print()
    
    

    Output:

    Output of Read function is
    Hello
    This is Delhi
    This is Paris
    This is London
    
    
    
    Output of Readline function is
    Hello

     

Leave a Comment

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

Scroll to Top