Python File Handling

Reading from a Text File:

Reading from a text report in Python is a not unusual operation, and it could be done the usage of the built-in open() feature at the side of the examine() or readlines() methods.

                                  
                                    # Open the file in read mode
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
                                  
                                

  • The open characteristic is used to open a document. The first argument is the report name, and the second one argument is the mode ("r" for read, "w" for write, "a" for append, and extra).
  • The with announcement is used for higher document managing. It ensures that the document is nicely closed after the block of code is carried out.

Writing to a Text File:

Writing to a text document in Python is also a not unusual operation and can be done the use of the open() function with the 'w' (write) mode. If the record does now not exist, it will be created. If it already exists, the content material can be overwritten.

                                  
                                    # Open the file in write mode
with open("example_write.txt", "w") as file:
    file.write("Hello, Python!\n")
    file.write("This is an example.")
                                  
                                

Reading Line by Line:

Reading a file line by using line in Python is a common operation, in particular for huge files in which reading the entire content right now might be impractical. You can obtain this the use of a loop or by way of the use of the readline() approach.

                                  
                                    with open("example_lines.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # Remove newline characters
                                  
                                

Appending to a File:

Appending to a record in Python is carried out using the 'a' (append) mode when opening the report. This allows you to feature new content to the give up of an existing record with out overwriting its modern content.

                                      
                                        with open("example_write.txt", "a") as file:
    file.write("\nAppending a new line.")
                                      
                                    

Reading and Writing Binary Files:

Reading and writing binary documents is just like operating with textual content documents, however you use the 'rb' (study binary) and 'wb' (write binary) modes when establishing the report.

                                      
                                        # Writing binary data to a file
with open("binary_data.bin", "wb") as file:
    file.write(b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64')

# Reading binary data from a file
with open("binary_data.bin", "rb") as file:
    data = file.read()
    print(data)
                                      
                                    

Using are searching for to Move the File Cursor:

The are seeking for() method is used to transport the file cursor to a distinctive position inside a document. The report cursor represents the contemporary position from wherein the next study or write operation will occur.

                                      
                                        with open("example.txt", "r") as file:
    file.seek(5)  # Move the cursor to the 5th byte
    content = file.read()
    print(content)
                                      
                                    

Handling Exceptions in File Operations:

When running with report operations in Python, it is critical to deal with exceptions correctly to account for capability mistakes that can arise in the course of document studying or writing. Common exceptions encompass FileNotFoundError, PermissionError, and IOError.

                                      
                                        try:
    with open("nonexistent_file.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("File not found.")
except Exception as e:
    print("An error occurred:", e)
                                      
                                    

File coping with in Python is critical for obligations like facts input/output, log report processing, and more. Understanding the way to read and write documents lets in you to engage with external information sources and shop data generated with the aid of your packages.