INTRODUCTION
Python file handling works on files like Text files, Binary files, and CSV files. Computers understand everything in a file format only like mp3 files for sound, mp4 files for video, and test files. We people are generating data regarding information, images, audio files, video files, etc. Till this point, to store data permanently we 📁 It's crucial to utilize data file handling to efficiently manage and store your data. This essential tool can help you save valuable ⏰ and effort. Make sure you're taking advantage of this feature to ensure that you're able to handle your data with ease.
TYPES OF FILES
Text file : A text file can be understood as a sequence of characters consisting of alphabets, numbers and other special symbols. Files with extensions like .txt, .py, .csv, etc. are some examples of text files
Binary Files: Binary files are also stored in terms of bytes (0s and 1s),but unlike text files These files are not human readable. Thus, trying to open a binary file using a text editor will show some garbage values.We need specific software to read or write the contents of a binary file.
IMPORTANT TERMS & DEFINITIONS
1. Data. Raw facts and figures which we store.
2. Information: When we process the data into a meaningful statement that enhances our knowledge, it is known as information.
3. File: it is the sequence of data/information stored on the computer. Python allows us to store information in Text Mode, Binary Mode, and CSV file Mode.
4. Pickle Module: The Python pickle module is used for serializing and de-serializing a Python object structure. Pickle Module "serializes" the object first before writing.
5. Open function: it is a Python built-in function used to open a file for reading or writing. it returns an object of file that is used with other functions.
Syntax :
file_object=open(filename,mode)
6. File Name: it is the name of the which we want to open.
7. Mode: it tells the mode in which the file needs to be opened.
![]() |
| Python file Mode |

Closing a file
Once we are done with the read/write operations on a file, it is a good practice to close the file. Python provides a close() method to do so. While closing a file, the system frees the memory allocated to it. The syntax of close() is:
file_object.close()
Opening a file using with clause
WRITING TO A TEXT FILE
For writing to a file, we first need to open it in write or append mode. If we open an existing file in write mode,the previous data will be erased, and the file object will be positioned at the beginning of the file. On the other hand, in append mode, new data will be added at the end of the previous data as the file object is at the end of the file. After opening the file, we can use the following methods to write data in the file.
• write() - for writing a single string
• writelines() - for writing a sequence of strings


Comments
Post a Comment