top of page

Python File Handling: write() and readline()

  • Writer: abhijeet sinha
    abhijeet sinha
  • Mar 22
  • 1 min read

Python File Handling: write() and readline()

In this tutorial, we’ll create text files, write multiple lines, and read lines back using Python’s built-in file handling functions.

Cleaned + working code

Copy and run this code (make sure the folder test_folder exists):

```python # Write to sample.txt filepath = "test_folder/sample.txt" with open(filepath, "w", encoding="utf-8") as f: f.write("it is a new file\n") # Write to More_data.txt filepath = "test_folder/More_data.txt" with open(filepath, "w", encoding="utf-8") as f: f.write("this is the final practice\n") f.write("it is containing all the details\n") f.write("It is having,final details\n") # Read first 2 lines from More_data.txt filepath = "test_folder/More_data.txt" with open(filepath, "r", encoding="utf-8") as f: line1 = f.readline() line2 = f.readline() print(line1) print(line2) ```

Explanation

  • open(path, "w") creates the file (or overwrites it) and lets you write text into it.

  • f.write("...\n") writes a line. The \n moves the cursor to the next line.

  • open(path, "r") opens the file for reading.

  • readline() reads one line at a time (including the newline at the end, if present).

Common mistakes (fixed from the original)

  • Writing to f before opening the file first.

  • Missing line breaks between statements.

  • Incorrect indentation that places read code outside the file-open block.

 
 
 

Comments


bottom of page