Module6-File Handling M6
Module6-File Handling M6
• It's important to close the file after performing operations to free up system
resources.
file.close()
FILE HANDLING
• Different Modes:
• "r" (Read): Open for reading (default).
• "w" (Write): Open for writing. Creates a new file or truncates an existing one.
• "a" (Append): Open for writing. Creates a new file or appends to an existing one.
• "b" (Binary):Add to a mode to open the file in binary mode (e.g., "rb" or "wb").
• "x" (Exclusive creation): Opens the file for exclusive creation, and raises an error if
the file already exists.
4
Read and Write Operations:
partial_content = file.read(50)
# Writing to a file
file.write("Hello, World!\n")
file.writelines(["Line 1\n", "Line 2\n"])
File Closing (normal closing method)
• In Python, the close() method is used to close a file.
• It's important to close a file after using it to free up system resources. The
close() method is called on a file object.
# Syntax
file_handler.close()
• File object is deleted from memory and file is no more accessible unless
we open it again.
• If we do not close the file after program execution, python garbage
collector will destroy file object and closes file automatically.
• Don’t rely on garbage collector.
Other ways of File Closing
• File can be closed in two other different methods:
• Using exception handling
• Using with statement
• After opening the file while performing some operations (read, write, etc.), if
any exception occur in the flow of program (break the program and give
exception error), close function may not execute.
• In this situation, we can close the file using exception handling
# Syntax
try:
File_handler=open(file_name.txt, mode=‘r’)
# Operations
finally:
File_handler.close()
• Finally block execute always irrespective of exception occur or not and file
will be closed
Other ways of File Closing
• Using with statement: Using the with statement to open and automatically
close the file
# Syntax
with open(file_name.txt, 'w') as file_handler:
file_handler.write('Hello,World!')
# Operations
• Any other file operations can be done within this block
• File is automatically closed outside the with block
File object methods:
readable():This method is used to check whether file is readable or not. If it is
readable it will give True otherwise False
writable():This method is used to check whether file is writable or not. If it is
writable it will give True otherwise False
File_handler=open(file_name.txt, mode=‘r’)
File_handler.readable() # True
File_handler.writable() # False
File_handler.close()