Skip to content

python readline

In Python, the readline() method is used to read a single line from a file or an input stream. It is commonly used when working with text files to read data line by line. Here’s how you can use it:

# Open a file for reading
file_name = 'example.txt'
with open(file_name, 'r') as file:
    # Read lines one by one
    line = file.readline()
    while line:
        # Process the line
        print(line.strip())  # Strip to remove leading/trailing whitespace
        # Read the next line
        line = file.readline()

In this example, we:

  1. Open a file named ‘example.txt’ in read (‘r’) mode using a with statement. This ensures that the file is properly closed after reading.
  2. Use a while loop to read lines from the file one by one.
  3. Inside the loop, we use file.readline() to read each line and store it in the line variable.
  4. We strip any leading or trailing whitespace from the line using strip() to clean it up.
  5. The loop continues until there are no more lines to read.

You can also use readline() with standard input (keyboard input) to read lines entered by the user in a terminal:

# Read lines from standard input
while True:
    user_input = input("Enter a line (or press Enter to quit): ")
    if not user_input:
        break
    print("You entered:", user_input)

In this example, we use input() to read lines of text entered by the user until they press Enter without entering any text.

Remember to handle exceptions, such as FileNotFoundError when working with files, and ensure proper error handling and resource cleanup in real-world applications.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)