Lesson · 40 min · Free
Python File Handling
Python File Handling Python File Handling In the realm of pharmaceutical and biotechnological data science, the ability to efficiently manage and interact with data files is paramount. Whether you're processing patient r
Python File Handling
In the realm of pharmaceutical and biotechnological data science, the ability to efficiently manage and interact with data files is paramount. Whether you're processing patient records, analyzing genomic sequences, or extracting information from drug development reports, Python's file handling capabilities provide the robust tools necessary for these tasks. This lesson will equip you with the fundamental knowledge to read from, write to, and manipulate various file types, laying a crucial foundation for more advanced data operations. At its core, file handling in Python involves opening a file, performing operations (reading or writing), and then closing the file. Failing to close a file can lead to data corruption, resource leaks, or unexpected behavior, especially in multi-threaded environments or long-running applications. Python offers built-in functions and keywords to simplify this process and ensure proper resource management.
Opening and Closing Files
The primary function for interacting with files is open() . This function takes at least two arguments: the file path (a string) and the mode (another string) in which the file should be opened. Common modes include: 'r' : Read mode (default). Opens a file for reading. If the file does not exist, it raises a FileNotFoundError . 'w' : Write mode. Opens a file for writing. If the file exists, its contents are truncated (emptied). If the file does not exist, it creates a new file. 'a' : Append mode. Opens a file for appending. Data written to the file will be added to the end. If the file does not exist, it creates a new file. 'x' : Exclusive creation mode. Creates a new file and opens it for writing. If the file already exists, the operation fails with an FileExistsError . This is useful for ensuring you don't accidentally overwrite an existing file. 't' : Text mode (default). Handles files as text, encoding and decoding characters. 'b' : Binary mode. Handles files as raw bytes, useful for non-textual data like images or compiled binaries. You can combine text/binary modes with read/write/append modes, e.g., 'rb' for reading binary or 'wt' for writing text (which is the default for 'w' ). After performing operations, it's crucial to close the file using the close() method. However, a more Pythonic and safer way to handle files is using the with statement, also known as a context manager. When you use with open(...) as file_object: , Python automatically handles closing the file for you, even if errors occur during file operations. This prevents resource leaks and simplifies your code.
Example 1: Writing and Reading a Text File
# Writing to a text file file_path_write = "patient_data.txt" with open(file_path_write, 'w') as file_handle: file_handle.write("Patient ID: P001, Age: 45, Diagnosis: Hypertension\n") file_handle.write("Patient ID: P002, Age: 62, Diagnosis: Diabetes\n") file_handle.write("Patient ID: P003, Age: 30, Diagnosis: Asthma\n") print(f"Data written to {file_path_write}") # Reading from the text file file_path_read = "patient_data.txt" with open(file_path_read, 'r') as file_handle: content = file_handle.read() print(f"\nContent of {file_path_read}:\n{content}") # Reading line by line print("\nReading line by line:") with open(file_path_read, 'r') as file_handle: for line in file_handle: print(f"Line: {line.strip()}") # .strip() removes leading/trailing whitespace, including newline characters When dealing with larger files, reading the entire content into memory using .read() might not be efficient or feasible. In such cases, iterating over the file object directly (as shown in the second part of Example 1) allows you to process the file line by line, significantly reducing memory consumption. Alternatively, .readline() reads a single line, and .readlines() reads all lines into a list of strings.
Example 2: Appending to a File and Handling Errors
# Appending new data to the file file_path_append = "patient_data.txt" with open(file_path_append, 'a') as file_handle: file_handle.write("Patient ID: P004, Age: 50, Diagnosis: Arthritis\n") print(f"\nAppended new data to {file_path_append}") # Trying to open a non-existent file (demonstrates error handling) try: with open("non_existent_file.txt", 'r') as file_handle: print(file_handle.read()) except FileNotFoundError: print("\nError: The file 'non_existent_file.txt' was not found.") except Exception as e: print(f"\nAn unexpected error occurred: {e}") Error handling, as demonstrated in Example 2 with the try-except block, is crucial for robust applications. It allows your program to gracefully handle situations like missing files or permission errors, preventing crashes and providing informative feedback to the user or system administrator. For pharmaceutical data, ensuring data integrity and preventing accidental overwrites is critical, which is where modes like 'x' and careful error handling become invaluable.
Key Takeaways
Use open() with appropriate modes ( 'r' , 'w' , 'a' , 'x' , 't' , 'b' ) to interact with files. Always close files after use to prevent resource leaks and data corruption. The with statement is the preferred method for file handling as it ensures automatic file closure. Read entire files with .read() , process line by line by iterating over the file object, or use .readline() / .readlines() . Implement try-except blocks for robust error handling, especially for FileNotFoundError .
Practice Exercise
Imagine you have a CSV file named drug_inventory.csv with the following content (assume it exists): DrugName,Quantity,ExpiryDate Paracetamol,1000,2025-12-31 Amoxicillin,500,2024-06-15 Insulin,200,2023-10-01 Your task is to write a Python script that reads this file, identifies any drugs that have an expiry date before today's date (assume today is 2024-01-01 for this exercise), and then writes these expired drugs into a new file called expired_drugs.txt , with each entry on a new line. The output in expired_drugs.txt should only contain the drug name and its expiry date, formatted as "Drug: [DrugName], Expired: [ExpiryDate]".
Watch the full lesson — free
This topic is part of The Complete Python Bootcamp: Basics to Pharma & Data Science, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →