Everything About File Handling in python.
File handling is an essential aspect of programming, and Python provides various functions and methods to work with files. This includes reading from and writing to files, as well as other file operations like deleting, copying, and renaming.
Basic Operations
- Opening a File
- To work with files, you first need to open them using the
open()
function. - The syntax is:
open(filename, mode)
filename
: The name of the file you want to open.mode
: This specifies the purpose for which you want to open the file.- Common modes include:
'r'
: Read (default mode). Opens the file for reading.'w'
: Write. Opens the file for writing (creates a new file or truncates the existing file).'a'
: Append. Opens the file for appending (adds content to the end of the file).'b'
: Binary mode (e.g.,'rb'
for reading in binary mode,'wb'
for writing in binary mode).'x'
: Create. Creates a new file and opens it for writing; raises an error if the file already exists.'+'
: Read and write (e.g.,'r+'
,'w+'
).
2. Reading from a File
read(size)
: Readssize
bytes from the file. If no size is specified, it reads the entire file.readline()
: Reads a single line from the file.readlines()
: Reads all lines in a file and returns them as a list.
3. Writing to a File
write(string)
: Writes the string to the file.writelines(list_of_strings)
: Writes a list of strings to the file.
4. Closing a File
- Always close a file after you’re done working with it using the
close()
method. This ensures that all changes are saved, and resources are freed. - Alternatively, you can use the
with
statement, which automatically closes the file when the block is exited.
with open('example.txt', 'w') as file:
file.write('Hello, World!')
5. Appending to a File
- Use the
'a'
mode to add content to the end of an existing file.
with open('example.txt', 'a') as file:
file.write('\nAppended text')
6. File Positioning
tell()
: Returns the current file position.seek(offset, from_what)
: Changes the file position.offset
is the number of bytes to move, andfrom_what
determines the reference point (0 for start of the file, 1 for current position, 2 for end of the file).
Working with Different File Types
Text Files: Files that contain readable characters, like .txt
files.
- Use
'r'
,'w'
,'a'
modes.
Binary Files: Files that contain data in binary format, like images or executables.
- Use
'rb'
,'wb'
,'ab'
modes.
File Handling Libraries
Python’s built-in file handling capabilities are sufficient for most tasks. However, there are additional libraries that can be used for more advanced file handling:
os
Module
- Provides functions for interacting with the operating system, including file operations like deleting, renaming, and more.
- Common functions:
os.remove(filename)
: Deletes a file.os.rename(src, dst)
: Renames a file or directory.os.mkdir(directory_name)
: Creates a new directory.os.rmdir(directory_name)
: Removes an empty directory.os.path.exists(path)
: Checks if the path exists.
2. shutil
Module
- For high-level file operations like copying and moving files.
- Common functions:
shutil.copy(src, dst)
: Copies a file.shutil.move(src, dst)
: Moves a file or directory.shutil.rmtree(directory_name)
: Removes a directory and all its contents.
3. pathlib
Module
- Introduced in Python 3.4, this module provides an object-oriented approach to file handling and path operations.
- Useful classes and methods:
Path()
: Creates a Path object.Path.exists()
: Checks if the path exists.Path.is_file()
: Checks if the path is a file.Path.is_dir()
: Checks if the path is a directory.Path.open(mode)
: Opens the file with the specified mode.Path.mkdir()
: Creates a directory.
4. tempfile
Module
- This module generates temporary files and directories.
- Common functions:
tempfile.TemporaryFile()
: Creates a temporary file that will be deleted once it is closed.tempfile.NamedTemporaryFile()
: Similar toTemporaryFile
, but the file has a visible name in the file system.tempfile.TemporaryDirectory()
: Creates a temporary directory that will be deleted when it is no longer needed.
5. pickle
Module
- Used for serializing and deserializing Python objects (object serialization).
- Useful when you want to save Python objects to a file and retrieve them later.
import pickle
# Saving an object
with open('data.pkl', 'wb') as file:
pickle.dump(my_object, file)
# Loading an object
with open('data.pkl', 'rb') as file:
my_object = pickle.load(file)
Example
# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Appending to a file
with open('example.txt', 'a') as file:
file.write('Appended text\n')
# Using os to delete the file
import os
if os.path.exists('example.txt'):
os.remove('example.txt')
Best Practices
- Always close files after you’re done using them (use
with
statements). - Handle exceptions when working with files to prevent data loss.
- Use the appropriate mode (
'r'
,'w'
,'a'
,'b'
) depending on your needs. - Consider using
pathlib
for a more modern and object-oriented approach to file handling.
By using the built-in functions and additional libraries like os
, shutil
, pathlib
, tempfile
, and pickle
, Python provides a robust set of tools for file handling.
Real scenario:-
suppose you have one folder(target folder)inside that you have multiple folder(inside this folder you have multiple file and folder) and file, first question is how you can delete everything inside that target folder without deleting target folder itself? and second question how you can delete everything inside that along with target folder?
solution:-
1. Delete Everything Inside the Target Folder Without Deleting the Target Folder Itself
To delete all files and subdirectories within a target folder but keep the target folder itself intact, you can use the following approach:
import os
import shutil
def clear_target_folder_contents(target_folder):
# Loop through all entries in the target folder
for entry in os.listdir(target_folder):
entry_path = os.path.join(target_folder, entry)
if os.path.isdir(entry_path):
shutil.rmtree(entry_path) # Delete the directory and its contents
elif os.path.isfile(entry_path):
os.remove(entry_path) # Delete the file
# Specify the target folder
target_folder = '/path/to/your/target_folder'
# Clear the contents of the target folder
clear_target_folder_contents(target_folder)
2. Delete Everything Inside the Target Folder Along with the Target Folder Itself
To delete the target folder itself along with all its contents, you can use shutil.rmtree()
directly on the target folder.
import shutil
# Specify the target folder
target_folder = '/path/to/your/target_folder'
# Delete the target folder and all its contents
shutil.rmtree(target_folder)
Summary
- To delete only the contents inside the target folder without deleting the folder itself:
- Use
os.listdir()
to list all items. - Use
os.path.join()
to construct full paths. - Use
shutil.rmtree()
for subdirectories andos.remove()
for files.
2. To delete the target folder and everything inside it:
- Use
shutil.rmtree()
directly on the target folder.
Important Notes
- Be cautious with `shutil.rmtree(): It will delete everything in the specified directory tree. Always double-check the path to avoid accidental data loss.
- Test your scripts: Before running them on important directories, try them on test directories to ensure they work as expected.
Thank you for reading !!!
If you enjoy this article and would like to Buy Me a Coffee, please click here.
you can connect with me on Linkedin.