FILE HANDLING IN PYTYHON
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").
It returns a file object, which is stored in the variable file.
If the file does not exist, Python will raise a FileNotFoundError.
Step 2: Reading the File Content
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.
Example: Assume example.txt contains:
After file.read(), variable ‘content’ will store:
\n represents a newline character.
Step 3: Printing the Content
This prints the entire content of the file.
Output:
Step 4: Closing the File
The .close() method releases system resources used by the file.
It is important to close a file after reading/writing to avoid memory leaks or issues with
accessing the file later.
Improved Code Using with open()
Instead of manually closing the file, a better approach is to use with open(), which
ensures the file is closed automatically:
File Reading and Writing in Python
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().
1. Reading the Entire File (read())
2. Reading Line by Line (readline())
3. Reading All Lines into a List (readlines())
Writing to a File
Writing to a File (write())
If output.txt exists, this overwrites it.
If it does not exist, Python creates a new file.
Appending Data (append mode)
This adds text without overwriting existing content.
Reading & Writing (r+ mode)
Reads the file before writing new content.
Difference Between r+ and w+ in Python File Handling
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
file.tell() Returns current cursor position in bytes.
file.seek(offset, whence) Moves cursor to a specific position.
Example: Using tell() and seek()
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.
1. Working with Directories Using the os Module
Checking the Current Directory (os.getcwd())
The current working directory (CWD) is where Python executes commands.
2. Changing the Directory (os.chdir())
To switch to another directory(folder):
3. Listing Files and Directories (os.listdir())
To list all files and folders inside a directory:
4. Creating a New Directory (os.mkdir())
To create a single directory:
5. Copying a Directory (shutil.copytree())