Lesson 9 – File handling

  • File handling in Python

    Python supports read and write operations on files.
    Python’s inbuilt function open() is used for file operations. But at the time of opening, we have to specify the mode.

    f = open(filename, mode)

    Where mode can take any of the following values

    r: open an existing file for a read only operation.

    w: open an existing file for a write operation. If the file already contains some data then it will be overridden.

    a:  open an existing file for append operation. In this case, it won’t override existing data.

     r+:  To read and write data into the file. The previous data in the file will be overridden.

    w+: To write and read data. It will override existing data.

    a+: To append and read data from the file. It won’t override existing data.

    Reading a file

    Example:

    Create a file called notes.txt and enter some lines of text

    file = open(‘notes.txt’, ‘r’)
    # This will print every line one by one in the file
    for each in file:
        print (each)

    Writing into a file

    In the example below, the mynotes.txt file will be created in the temp directory in C drive

    file = open(“C:/temp/mynotes.txt”,’w’)
    file.write(“I am writing first line”)
    file.write(“I am writing 2nd line”)
    file.close()

    Now check the file, in the temp directory. As the file is opened in “w’ mode, the 2nd line overwrites the first line. 


    Writing into a file ( append mode)

    file = open(“C:/temp/mynotes.txt”,’a’)
    file.write(“I am writing first line”)
    file.write(“I am writing 2nd line”)
    file.close()
    This will ensure, the contents in the file are not overwritten