Class 12 Computer Science Chapter 2 - File Handling in Python
Introduction to File Handling
File handling is an essential aspect of programming, enabling the storage, retrieval, and manipulation of data on disk. Python provides built-in functions and modules to handle file operations such as reading, writing, appending, and more. Types of Files 1. Text Files: o Store data in human-readable format. o Examples: .txt, .csv, .html. 2. Binary Files: o Store data in binary format (non-readable by humans). o Examples: .bin, .exe, .jpg. File Operations 1. Opening a File: o Files can be opened using the open() function. o Syntax: file_object = open(filename, mode) o Common Modes: 'r': Read mode (default mode). 'w': Write mode. 'a': Append mode. 'b': Binary mode (used with other modes like 'rb', 'wb'). '+': Read and write mode (used with other modes like 'r+', 'w+'). 2. Reading from a File: o read(size): Reads specified number of characters from the file. If size is omitted, it reads the entire file. o readline(): Reads a single line from the file. o readlines(): Reads all lines from the file and returns them as a list. Example: python Copy code with open('example.txt', 'r') as file: content = file.read() print(content) 3. Writing to a File: o write(string): Writes the specified string to the file. o writelines(list): Writes a list of strings to the file. Example: python Copy code with open('example.txt', 'w') as file: file.write('Hello, world!\n') file.writelines(['Line 1\n', 'Line 2\n']) 4. Appending to a File: o Similar to writing, but the content is added to the end of the file instead of overwriting it. Example: python Copy code with open('example.txt', 'a') as file: file.write('Appended text.\n') 5. Closing a File: o It's essential to close a file after performing operations to free up system resources. o file.close() o Using the with statement automatically closes the file after the block is executed. File Handling Functions • open(): Opens a file and returns a file object. • read(size): Reads size bytes from the file. • readline(): Reads a single line from the file. • readlines(): Reads all lines from the file. • write(string): Writes a string to the file. • writelines(list): Writes a list of strings to the file. • close(): Closes the file. Working with Text Files Example to read from a text file: python Copy code with open('example.txt', 'r') as file: data = file.read() print(data) Example to write to a text file: python Copy code with open('output.txt', 'w') as file: file.write('This is a sample text.') Working with Binary Files Reading from a binary file: python Copy code with open('image.jpg', 'rb') as file: data = file.read() print(data) Writing to a binary file: python Copy code with open('output.bin', 'wb') as file: file.write(b'\x00\x01\x02\x03') File Handling using os and os.path Modules 1. Checking if a File Exists: python Copy code import os if os.path.exists('example.txt'): print('File exists.') else: print('File does not exist.') 2. Deleting a File: python Copy code os.remove('example.txt') 3. Renaming a File: python Copy code os.rename('old_name.txt', 'new_name.txt') 4. Creating a Directory: python Copy code os.mkdir('new_directory') 5. Deleting a Directory: python Copy code os.rmdir('new_directory') Exception Handling in File Operations Using try-except to handle file operation errors: python Copy code try: with open('example.txt', 'r') as file: data = file.read() print(data) except FileNotFoundError: print('File not found.') except IOError: print('Error while reading the file.') Summary File handling is a crucial aspect of programming that allows for the efficient storage, retrieval, and manipulation of data. Python provides a robust set of functions and methods to handle files, ensuring that data operations are performed smoothly and efficiently. Proper exception handling ensures that any errors during file operations are managed gracefully, maintaining the stability and reliability of the program.