Google News
logo
Python Program to Read only parts of a file
In the following example of a Python program that demonstrates how to read only parts of a file :
Program :
try:
    with open('example.txt', 'r') as file:
        # Read the first 10 characters of the file
        first_part = file.read(10)
        print("First 10 characters of the file:")
        print(first_part)

        # Read the next 5 characters of the file
        second_part = file.read(5)
        print("Next 5 characters of the file:")
        print(second_part)

        # Read the rest of the file
        rest = file.read()
        print("The rest of the file:")
        print(rest)
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 `read()` method is used to read the first 10 characters of the file into the `first_part` variable. The next 5 characters are then read into the `second_part` variable using the `read()` method again. Finally, the `read()` method is used without any arguments to read the rest of the file into the `rest` variable.

Note that the `read()` method returns an empty string when it reaches the end of the file. This means that the third call to `read()` will return an empty string if the first two calls have already read the entire file.

You can adjust the arguments passed to the `read()` method to read different parts of the file. For example, you could read the first line of the file by calling `file.readline()`, or you could read a specific number of lines by passing an argument to the `readlines()` method.