How to Use Python `read()` Function to Read Files in Bytes (Characters) With Examples

In Python, file handling is a crucial aspect of many applications. The `read()` function, commonly used for reading files, plays a significant role in retrieving data from files in byte or character format. By using this function, developers can extract specific information from files and process it accordingly.

1. Understanding the `read()` Function.

  1. The `read()` function in Python is employed to read a specified number of bytes (or characters if the file is opened in text mode) from a file.
  2. When used without an argument, it reads the entire contents of the file.
  3. This function is particularly useful when dealing with large data files or when developers need to process data in chunks.

1.1 Syntax of the `read()` Function.

  1. The syntax for using the `read()` function is as follows:
    file_object.read(size)
    
  2. Here, `file_object` represents the file to be read, and `size` denotes the number of bytes or characters to read from the file.
  3. If no argument is provided, the entire file is read.

2. Examples of Using the `read()` Function.

2.1 Example 1: Reading the Entire File.

  1. Source code.
    def read_entire_file():
        # Open file in read mode
        file = open('example.txt', 'r')
    
        # Read the entire file
        data = file.read()
    
        # Print the contents
        print(data)
    
        # Close the file
        file.close()
    
    
    if __name__ == "__main__":
        read_entire_file()
  2. Output.
    Hello, Python.
    This text is appended to the file.

2.2 Example 2: Reading a Specific Number of Characters.

  1. Source code.
    def read_special_number_of_characters():
        # Open file in read mode
        file = open('example.txt', 'r')
    
        # Read the first 10 characters
        data = file.read(10)
    
        # Print the contents
        print(data)
    
        # Close the file
        file.close()
    
    
    if __name__ == "__main__":
        read_special_number_of_characters()
  2. Output.
    Hello, Pyt

2.3 Example 3: Reading All File Content by Chunks.

  1. Source code.
    def read_all_file_by_chunks():
        # Open file in read mode
        file = open('example.txt', 'r')
    
        # Define chunk size
        chunk_size = 100
    
        # Read the file in chunks
        while True:
            data = file.read(chunk_size)
            if not data:
                break
            print(data)
    
        # Close the file
        file.close()
    
    if __name__ == "__main__":
        read_all_file_by_chunks()
  2. Output.
    Hello, Python.
    This text is appended to the file.

2.4 Example 4: Reading File in Binary Mode.

  1. Source code.
    def read_file_in_binary_mode():
        # Open file in binary read mode
        file = open('example.txt', 'rb')
    
        # Read the entire file in binary format
        data = file.read()
    
        # Print the contents
        print(data)
    
        # Close the file
        file.close()
    
    
    if __name__ == "__main__":
        read_file_in_binary_mode()
  2. Output.
    b'Hello, Python.\r\nThis text is appended to the file.'
  3. Below is the binary content saved in another file output.txt.
    ���Python����
  4. We can use the below source code to read the binary content out.
    def read_file_in_binary_mode():
        # Open file in binary read mode
        file = open('output.txt', 'rb')
    
        # Read the entire file in binary format
        data = file.read()
    
        # Print the contents
        print(data)
    
        str_data = data.decode('gb2312')
        print(str_data)
    
        # Close the file
        file.close()
    
    
    if __name__ == "__main__":
        read_file_in_binary_mode()
  5. Output.
    b'\xc4\xe3\xba\xc3Python\xca\xc0\xbd\xe7'
    你好Python世界

2.5 Example 5: Copy File by Reading and Writing Binary Data.

  1. Source code.
    def copy_file():
        # Open file in binary read mode
        input_file = open('output.txt', 'rb')
    
        # Open file in binary write mode
        output_file = open('output1.txt', 'wb')
    
        # Read data from input file
        data = input_file.read()
    
        # Write data to output file
        output_file.write(data)
    
        print(input_file.closed)
        # Close the files
        input_file.close()
        print(input_file.closed)
    
        output_file.close()
    
    
    if __name__ == "__main__":
        copy_file()
    
  2. Output: You can see the file output1.txt is created with the same content of output.txt.

2.6 Example 6: Using with Statement for Automatic File Closure.

  1. Source code.
    def use_with_statement_for_auto_close_file():
        # Using 'with' statement to automatically close the file
        with open('example.txt', 'r') as file:
            # Read the entire file
            data = file.read()
    
        # File is automatically closed outside the 'with' block
        print(data)
    
        if file.closed:
            print('file is closed')
    
    
    if __name__ == "__main__":
        use_with_statement_for_auto_close_file()
  2. Output.
    Hello, Python.
    This text is appended to the file.
    file is closed

2.7 Example 7: Reading a File with Encoding Specification.

  1. Source code.
    def read_file_with_special_encoding():
        # Open file with specific encoding
        with open('output.txt', 'r', encoding='gb2312') as file:
            # Read the entire file
            data = file.read()
    
        # Print the contents
        print(data)
    
    
    if __name__ == "__main__":
        read_file_with_special_encoding()
  2. Output.
    你好Python世界

2.8 Example 8: Iterating through a Text File Line by Line.

  1. Source code.
    def iterate_through_text_file_line_by_line():
        # Open file in read mode
        with open('example.txt', 'r') as file:
            # Iterate through each line
            for line in file:
                print(line, end='')
    
    
    if __name__ == "__main__":
        iterate_through_text_file_line_by_line()
  2. Output.
    Hello, Python.
    This text is appended to the file.

2.9 Example 9: Reading and Splitting File Data.

  1. Source code.
    def read_and_split_file_data():
        # Open file in read mode
        with open('example.txt', 'r') as file:
            # Read the entire file and split by whitespace
            words = file.read().split()
    
        # Print the words
        print(words)
    
    
    if __name__ == "__main__":
        read_and_split_file_data()
  2. Output.
    ['Hello,', 'Python.', 'This', 'text', 'is', 'appended', 'to', 'the', 'file.']

3. Conclusion.

  1. The `read()` function is a powerful tool in Python for reading files in bytes or characters. With its various applications and easy-to-use syntax, it provides developers with the flexibility to handle file data efficiently.
  2. By mastering the `read()` function, developers can efficiently read and process data from files in their Python applications.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.