Python File I/O

    In this tutorial, we will discuss Python File I/O.  We will learn how to open a file and how to write and read it. So let us get started!

    Python File I/O

    File in Python

    With the help of python, we can create a new txt file or use the old ones, to write and read. When we create a file with the help of python it stores in the same location where we have written our python script. Procedure to read and write from a file:

    • Open the file
    • Read or write
    • Close the file

    Open or Create a file:

    To open a file we use the open() function, this function will create a new file if there isn’t any or else it will use the old file.

    Opening file Syntax:

    f = open("file name", file_mode) #here f is the file object known as handle
    
    Example:
    f = open("file.txt", w)      # Here we have passed the ‘ w ’ mode which means we are opening this file to write something

    Normally we use w, a and r mode to write, append and read respectively. Python File Modes:

    Mode Details
    r Open file to read
    w Open file to write
    x Open file for exclusive creation
    a Open the file to append the write function
    t Open in text mode
    b Open in binary mode
    + Open a file for reading and writing

    Example :

    f = open("file.txt") # by default read mode
    f = open("file.txt", 'w') # open file for write mode
    f = open("file.txt",'a') #open file for append
    f = open("file.txt", 'r+b') #open file in read and binary mode 

    Close a File using Python:

    Once we open a file and done with reading or writing methods, we need to close it. To close a file we use the close() method. Example:

    f = open("file.txt",'w')
    f.close()  # close a file

    If you forget to close the file, the file could get garbage values so it's necessary to close the file once we have done with it. Though there is a technique in which we do not need to close the file explicitly. To close the file implicitly without calling the close() method we use with keyword to open the file. Example:

    with open("file.txt" , 'w')  as   f:     #Here f is the file object

    Write in a File:

    To write in a file we can open the file with 3 modes ‘w’ write mode or ‘a’ append mode or ‘x’ exclusive creation mode. When we write in a file with ‘w’ mode it overwrites the previous data if the file is already existing. So, we normally open file with ‘w’ mode when we write in a new file or we want to overwrite the old one. When we write in a file with ‘a’ append mode it does not overwrite the previous data instead it continues from it. Once the file is open and we have assigned a mode to it we can write in the file with the help of write() method. This write() method return a sequence of character and write it in the txt file. Syntax to write in a file:

    with open ("file name with txt extension", 'w') as file_object:
        file_object.write("statement which you want to write in the txt file")

    Example:

    with open ("file.txt", 'w') as f:
        f.write("hello this is written in file.txt")
        f.write("it's in 2nd line")
        print("this statement would not be written in the file ")

    #Output

    this statement would not be written in the file

    #In file.txt

    hello this is written in file.txt
    it's in 2nd line

    Behind the code: Once you run this code a txt file will be created at the same location where this script is. You can visit that location on your computer and open it. The above code is equivalent to:

    f=open ("file.txt", 'w')
    f.write("hello this is written in file.txt")
    f.write("\nit's in 2nd line")
    print("this statement would not be written in the file ")
    f.close()

    Read from the file: To read from a file first we need to open the file in reading mode. Once the file is open with the help of read() method we can read the text written in the file. In the read() method we can also pass some integer value as an argument and the read method will only read that many characters. Syntax to read form a file

    with open ("file name with txt extension", r) as file_object:
         file_object.read(size)                     
                          OR
    file_object = open("file name", r)
    file_object.read()

    Example: Here we will read that file which we have created using the write mode in the above example:

    f=open ("file.txt", 'r')      #Opening the file
    print(f.read(6))                 #read first 6 characters
    print(f.read(5))                 # read next 5 characters
    print(f.read())                    # read all that’s left

    #Output

    hello
    this
    is written in file.txt
    it's in 2nd line

    There are many other methods that can read from the files such as readline (), this method is used to read a single line. When we read from a file a pointer moves from 1 st character to the last character, you can not read a file twice using two consecutive read() methods because once the pointer reaches the last character we could not read the file again to do so we need to run it again. tell() this method is used to tell us where is our pointer right now seak() , this method can bring our cursor at the 1 st character. Let’s take an example:

    f=open ("file.txt", 'r')
    print("pointer location before we read the file: ", f.tell())
    print(f.read())
    print("pointer location once we read the complete file(): ",f.tell())
    print("------- using read method again--------")
    print("this read method would not be able to read any thing:",f.read())
    print("-------  using seek method -------")
    f.seek(0)
    print("pointer location after using the seek method: ", f.tell())
    print ("----------using readline method-----------")
    print(f.readline()) 
    

    #Output

    pointer location before we read the file:  0
    hello this is written in file.txt
    it's in 2nd line
    pointer location once we read the complete file():  51
    ------- using read method again--------
    this read method would not be able to read any thing:
    -------  using seek method -------
    pointer location after using the seek method:  0
    ----------using readline method-----------
    hello this is written in file.txt

    Python File Methods:

    There are many file methods here we have mentioned the importance once.

    • close()
    • detach()
    • fileno()
    • flush()
    • isatty()
    • read(n)
    • readable()
    • readline(n=-1)
    • readlines(n=-1)
    • seek(offset,from=SEEK_SET)
    • seekable()
    • tell()
    • truncate(size=None)
    • writable()
    • write(s)
    • writelines(lines)

    Python Tutorials:

    Introduction

    Flow Control

    Functions

    Datatypes

    File Handling

    Object & Class

    Additional Tutorials