FILE HANDLING IN PYTHON
FILE HANDLING IN PYTHON
File handling in Python allows us to create, read, write, and manage files easily. It is useful for storing
and retrieving data, such as saving user information, logging errors, or processing text files. Python
provides built-in functions to work with files using the open() function, which opens a file in
different modes like read ('r'), write ('w'), append ('a'), and more. To read a file, we use
file.read(), and to write data, we use file.write(). It is important to close a file after use
with file.close().
In file.read(), the variable file is a file object that represents the opened file. When we use
the open() function in Python, it returns a file object, which we can use to perform file operations
like reading, writing, or appending data.
Code Explanation:-
Step 1: Opening the File
The open() function is used to open the file named "example.txt" in read mode ("r").
The .read() method reads the entire content of the file and stores it in the variable
content.
The file pointer (cursor) moves to the end of the file after reading.
Output:
It is important to close a file after reading/writing to avoid memory leaks or issues with
accessing the file later.
Instead of manually closing the file, a better approach is to use with open(), which
ensures the file is closed automatically:
File handling in Python allows us to read from and write to files efficiently. The open() function is
used to access files, and it supports different modes:
Reading a File
We can read a file using different methods like .read(), .readline(), or .readlines().
Both r+ and w+ modes allow reading and writing, but they behave differently in file handling.
File Pointer Manipulation
Python tracks the cursor position in a file. We can move or check it using:
Method Description
The tell() and seek() methods in Python are used for file pointer manipulation. The tell()
method returns the current position of the file pointer in bytes, helping track where reading or
writing is happening. The seek(offset, whence) method moves the pointer to a specific
position; offset defines the number of bytes to move, and whence (default 0) determines the
reference point (0 = beginning, 1 = current position, 2 = end). For example, file.seek(0) moves
the pointer to the start, while file.seek(5, 0) moves it to the 5th byte. These methods are
useful for modifying files without reloading them entirely.
Directories in Python
A directory (folder) is a storage location that can contain multiple files and subdirectories. Python
provides the os and shutil modules to work with directories, allowing users to create, delete,
rename, and navigate through folders.