Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module 4 Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

MODULE: 4 Python

what is File Management in Python:


File Management in Python refers to the process of handling files for tasks like
reading, writing, creating, and updating files. Python provides built-in functions
to manage files, allowing you to store and retrieve data efficiently.
Why File Management is Important:
 Storing data: You often need to save data generated by a program, such
as logs, results, or user input.
 Accessing external data: Programs may need to read data from files like
text files, CSV files, or JSON files.
 Persistent storage: Files allow data to be saved permanently, unlike
variables that disappear when the program stops running.
Main Tasks in File Management:
1. Opening a file: Before performing any operation (read/write), a file
needs to be opened using the open() function.
2. Modes of operation: You can specify how the file is accessed (e.g., read-
only, write, append).
3. Reading/writing data: Once the file is opened, you can either read the
contents or write new content.
4. Closing a file: After performing the necessary operations, it’s important
to close the file to release system resources.
Example of File Management in Python:
Here’s a simple example to demonstrate basic file handling:
# Open a file for writing
with open("example.txt", "w") as file:
file.write("This is a sample text.")

# Open a file for reading


with open("example.txt", "r") as file:
content = file.read()
print(content) # Output: This is a sample text.
Operations on Files in Python:
File operations refer to working with files, such as opening a file, using file
modes, checking file attributes, understanding file encoding, and closing a file.
1. Opening Files
To work with a file, you need to first open it. In Python, the open() function is
used:
file = open("filename.txt", mode)
Here, "filename.txt" is the file you want to open, and mode specifies the action
you want to perform (read, write, etc.).
2. File Modes
The mode argument specifies what you want to do with the file:
 'r': Read (default mode). Opens the file for reading. If the file doesn’t
exist, it raises an error.
 'w': Write. Opens the file for writing. If the file exists, it overwrites it. If it
doesn't exist, it creates a new one.
 'a': Append. Opens the file for appending data at the end. If it doesn’t
exist, it creates a new file.
 'b': Binary mode. Used with other modes ('rb', 'wb', etc.) to read or write
in binary format.
 'x': Exclusive creation mode. Creates a new file. Raises an error if the file
already exists.
Example:
file = open("data.txt", "r") # Opens file for reading
3. File Attributes
After opening a file, you can access certain attributes:
 file.name: Returns the name of the file.
 file.mode: Returns the mode in which the file was opened.
 file.closed: Returns True if the file is closed, False otherwise.
Example:
print(file.name) # Output: data.txt
print(file.mode) # Output: r
print(file.closed) # Output: False
4. Encoding
Encoding is important when working with text files containing special
characters. You can specify the file encoding while opening it:
 utf-8: The most common encoding, supports most characters.
 ascii: Limited to English characters.
Example:
file = open("data.txt", "r", encoding="utf-8")
5. Closing Files
After completing operations on a file, you should close it to free up system
resources. Use the close() method:
Example:
file.close()
You can also manage files using the with statement, which automatically closes
the file after the block of code is executed:
with open("data.txt", "r") as file:
content = file.read()
# The file is automatically closed after the block
read() & write() Methods
o read(): This method is used to read data from a file. You can
specify how many characters to read or leave it blank to read the
entire file.
o write(): This method is used to write data into a file. It overwrites
the existing content if you open the file in write mode.
 Example:

with open("example.txt", "r") as file:


content = file.read() # Reading entire file
print(content)

with open("example.txt", "w") as file:


file.write("This is new content.") # Writing to the file

tell() & seek() Methods


 tell(): This method returns the current position of the file pointer (where the
next character will be read or written).
 seek(): This method is used to change the file pointer's position. You can
move the pointer to any position in the file.
Example:
with open("example.txt", "r") as file:
print(file.tell()) # Current position of pointer
file.seek(5) # Move pointer to 5th character
print(file.read()) # Read from 5th character onward

Renaming & Deleting Files in Python


Python’s os module allows you to rename or delete files:
 Renaming a file: Use os.rename("old_filename", "new_filename") to
rename a file.
 Deleting a file: Use os.remove("filename") to delete a file.
Example:
import os
os.rename("oldfile.txt", "newfile.txt") # Renaming file
os.remove("newfile.txt") # Deleting file

Directories in Python
Directories are folders used to organize files. Python’s os module provides
functions to work with directories:
 Creating a directory: Use os.mkdir("directory_name") to create a new
directory.
 Changing the directory: Use os.chdir("directory_name") to change the
current working directory.
 Listing files in a directory: Use os.listdir("directory_name") to list all
files and directories inside a directory.
 Deleting a directory: Use os.rmdir("directory_name") to remove an
empty directory.
Example:
import os
os.mkdir("new_folder") # Creating a new directory
os.chdir("new_folder") # Changing the current directory
print(os.listdir()) # Listing contents of the directory
os.rmdir("new_folder") # Deleting the directory

You might also like