Google News
logo
Python Program to Read one line of a file
In the following example of a Python program that demonstrates how to read one line of a file :
Program :
try:
    with open('example.txt', 'r') as file:
        # Read one line of the file
        line = file.readline()
        print("One line of the file:")
        print(line)
except FileNotFoundError as e:
    print(f"File not found: {e}")
except Exception as e:
    print(f"An error occurred: {e}")
In this example, the `open()` function is used to open the file named "example.txt" in read-only mode, and the `with` statement is used to ensure that the file is properly closed after it has been read. The `readline()` method is used to read one line of the file into the `line` variable.

Note that the `readline()` method reads until it reaches a newline character (`\n`) or the end of the file, whichever comes first. If the file does not contain any newline characters, the entire file will be read as a single line.

You can use a loop to read multiple lines of the file, like this :
Program :
try:
    with open('example.txt', 'r') as file:
        # Read and print each line of the file
        for line in file:
            print(line)
except FileNotFoundError as e:
    print(f"File not found: {e}")
except Exception as e:
    print(f"An error occurred: {e}")
In this example, a `for` loop is used to iterate over the lines of the file one by one. Each line is printed to the console. This approach is useful if you want to read the entire file or a specific subset of lines.