
File Handling in Python
File Handling
- File handling in Python involves working with various types of files, including text files, binary files, and CSV files.
- You can perform a range of operations on files, such as creating, writing, appending, inserting, deleting, updating, and modifying data.
Types of Files
- Text File: Text files contain human-readable text and are typically encoded in plain text formats like ASCII or UTF-8.
- Binary Files: Binary files contain non-textual data and can be in various formats, such as images, audio, or any data that doesn't follow plain text encoding.
- CSV File: CSV (Comma-Separated Values) files store tabular data in plain text form, with values separated by commas.
Creating and Writing to a Text File in Python
- To create a new file, you can use the built-in open() function with the 'w' (write) mode for text files or 'wb' (write binary) mode for binary files.
- Here's an example of creating a text file and writing data:
Loading…
Appending Data to Files
- To append data to an existing file, you can use the 'a' (append) mode.
- Here's an example:
Loading…
Insertion, Deletion, and Modification of Data
- Inserting, deleting, and modifying data in a file is more complex and typically involves reading the file, making the necessary changes in memory, and then writing the updated data back to the file.
- Here's an example of modifying a specific line in a text file:
Loading…
For insertion and deletion, you would manipulate the lines list accordingly.
Conclusion
- File handling is an essential part of working with data in Python.
- You can create, write, append, insert, delete, update, and modify data in text and binary files.