
Step 3: Once done, close the file handler using the close () function. Use the file handler inside your for-loop and read all the lines from the given file line-by-line. Step 2: The open () function will return a file handler. This method can be used to read the next input line, from the file object. First, open the file using Python open () function in read mode. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised. The handle is positioned at the end of the file.

The file is created if it does not exist. The definition of these access modes are as follows: Append Only (‘a’): Open the file for writing.

Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercise Python If.Else Python While Loops Python For Loops Python Functions Python Lambda Python Arrays Python Classes/Objects Python Inheritance Python Iterators Python Scope Python Modules Python Dates Python Math Python JSON Python RegEx Python PIP Python Try. Python 3 has a built-in function next () which retrieves the next item from the iterator by calling its next () method. In order to append a new line to the existing file, open the file in append mode, by using either 'a' or 'a+' as the access mode.
