Module8 - File Operations
Module8 - File Operations
• Files can be classified into different types based on their contents and purpose.
Some common types of files include:
# Append mode
with open('myfile.txt', 'a') as file:
file.write("\nThis is appended text.")
• Example:
file = open('myfile.txt', 'r')
# Perform operations on the file
file.close()
• Using with statement ensures that the file is properly closed after
its suite finishes, even if an exception is raised during the process.
You don’t need to explicitly close the file.
Renaming and Deleting Files
• You can use the os.rename() function to rename a file and
the os.remove() function to delete a file. Both functions are
in the os module.
• Example (Renaming):
import os
os.rename('oldfile.txt', 'newfile.txt')
• Example (Deleting):
• import os
• os.remove('myfile.txt')
Checking File Existence
• You can check if a file exists using the
os.path.exists() function, which returns True if the
file exists and False otherwise.
• Example:
import os
if os.path.exists('myfile.txt'):
print("File exists")
else:
print("File does not exist")
Seeking in a File
• You can use the seek() method to change the current file position.
This is useful when you want to move the file pointer to a specific
position within the file.
• Example:
file = open('myfile.txt', 'r')
file.seek(10) # Move to the 10th byte in the file
– Example:
try:
file = open('myfile.txt', 'r')
# Perform operations on the file
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
finally:
if 'file' in locals():
file.close()
Locals()
• In Python, locals() is a built-in function that returns a
dictionary representing the current local symbol table.
This dictionary contains all the variables defined in the
current scope. It's commonly used within functions to
access local variables.
def example_function():
a = 10
b = "Hello"
print(locals())
example_function()