0% found this document useful (0 votes)
5 views

Module6-File Handling M6

The document provides an introduction to file handling in Python, explaining the importance of files for storing data and the various operations that can be performed on them, such as opening, reading, writing, and closing files. It details different file modes, methods for reading and writing, and techniques for ensuring files are properly closed, including exception handling and the use of the 'with' statement. Additionally, it includes examples of Python programs for various file operations, such as counting words, merging files, and modifying file contents.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Module6-File Handling M6

The document provides an introduction to file handling in Python, explaining the importance of files for storing data and the various operations that can be performed on them, such as opening, reading, writing, and closing files. It details different file modes, methods for reading and writing, and techniques for ensuring files are properly closed, including exception handling and the use of the 'with' statement. Additionally, it includes examples of Python programs for various file operations, such as counting words, merging files, and modifying file contents.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

INTRODUCTION TO FILE

• A file is a collection of data stored on a secondary storage device, such as a hard


disk.
• Files are used to store information in a structured and organized manner.
• A file is basically used because real-life applications involve large amounts of
data and in such situations the console oriented I/O operations pose two major
problems:
 It becomes cumbersome and time consuming to handle huge amount of data through
terminals.
 When doing I/O using terminal, the entire data is lost when either the program is
terminated or computer is turned off. Therefore, it becomes necessary to store data
on a permanent storage (the disks) and read whenever necessary, without destroying
the data.
File handling in Python involves various operations, including reading from and
writing to files.
Opening a File :To open a file, use the open() function. It takes two arguments
such as the file path and the mode.

Opening and Closing Files:


• To open a file, you can use the open() function. It takes two arguments: the
file path and the mode.

# Opening a file in 'read' mode


file = open("example.txt", "r")

• 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:

# Reading the entire file


content = file.read()

# Reading a specific number of characters

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()

Check file existing:


isfile() method is used to check file exist or not. It will give True/False
This method belongs to path module which is submodule of os module.
Synax import os
os.path.isfile(file_name)
Reading a file using for loop:
File_handler=open(file_name.txt, mode=‘r’)
for line in File_handler:
print(line)
File_handler.close

Reading a file using list:


File_handler=open(file_name.txt, mode=‘r’)
print(list(File_handler))
tell() and seek() methods:
• The tell() method returns the current position of the file cursor (pointer) in
the file.
• It provides the byte offset from the beginning of the file where the next read
or write operation will occur.
# Example using tell() method
with open(‘file.txt', 'r') as f:
content = f.read(10) # Read the first 10 characters
position = f.tell() # Get the current position
print(f"Content: {content}")
print(f"Current Position: {position}")
• The seek(offset, whence) method is used to change the file cursor position to
a specified offset.
• It allows to move the cursor to a specific position in the file before performing
read or write operations.
• offset specifies the number of bytes to move the cursor.
• whence specifies the reference position for the offset. It can take three
values:
• 0 (default): Offset is relative to the beginning of the file.
• 1: Offset is relative to the current position of the cursor.
• 2: Offset is relative to the end of the file.

# Example using seek() method


with open(‘file.txt', 'r') as f:
f.seek(5) # Move cursor to the 6th byte from the beginning
content = f.read(10) # Read 10 characters from the current position
print(f"Content: {content}")
• Write a python program to reads a text file named file_demo.txt, then
counts the number of lines, characters, and words in that file.
Write a python code that copies the content of one text file (file_demo.txt)
to another text file (file_demo1.txt)
write the code to search a particular word (string to be taken by the user during run-time only) in
the content of file_demo.txt and display the number of occurrence of this particular word. In the
last part of the question, copy all the even indexed characters in file_demo2.txt and odd indexed
characters in file_demo3.txt.
Q.1 write a python program to create a file and write contents, save and close the file.
Q.2 Write a python program to read file contents on console.
Q.3 print first and last character present in the file.
Q.4 write a python program to compare two files.
Q.5 write a python program to merge two files to third
Q.6 write a python program to append content to a file
Q.7 write a python program to count number of words, characters and lines in a file.
Q.8 write a python program to remove certain word from file.
Q.9 write a python program to rename a file.
Q.10 write a python program to check weather file exist of not in directory.
Q.11 write a python program to convert uppercase to lowercase and vice versa in a text file
Q.12 write a python program to replace a specific line in text file.
Q.13 write a python program to print occurences of all words in text file.
Q.14 write a python program to find and replace a word in text file.
Q.15 write a python program to remove empty lines from a file.
Q.16 assign line numbers to every line of a text file.
Create a Python program that, given a user-input string, removes vowels at
positions divisible by 5 and prints the modified string. Additionally, generate
a list with the corresponding removed vowels as values.

You might also like