Python Lab Manual: File Handling
1. Introduction
File handling allows programs to read and write data to files stored on disk. Python provides
built-in functions and methods to work with files easily.
2. Opening a File
Use the open() function to open a file:
1 file = open ( " example . txt " , " r " ) # Open file for reading
Common modes:
• "r": Read (default)
• "w": Write (creates file or overwrites)
• "a": Append (write at the end)
• "x": Create (fails if file exists)
• "b": Binary mode (used with other modes)
• "+": Read and write
3. Closing a File
Always close files after use:
1 file . close ()
Or use with statement to automatically close:
1 with open ( " example . txt " , " r " ) as file :
2 content = file . read ()
1
Python Lab Manual File Handling
4. Reading Files
4.1 read()
Reads the entire file content as a string.
1 with open ( " example . txt " , " r " ) as file :
2 content = file . read ()
3 print ( content )
4.2 readline()
Reads one line at a time.
1 with open ( " example . txt " , " r " ) as file :
2 line = file . readline ()
3 while line :
4 print ( line , end = ’ ’)
5 line = file . readline ()
4.3 readlines()
Reads all lines into a list.
1 with open ( " example . txt " , " r " ) as file :
2 lines = file . readlines ()
3 print ( lines )
5. Writing Files
5.1 write()
Write a string to a file (overwrites existing content).
1 with open ( " output . txt " , " w " ) as file :
2 file . write ( " Hello , World !\ n " )
5.2 writelines()
Write a list of strings to a file.
1 lines = [ " First line \ n " , " Second line \ n " , " Third line \ n " ]
2 with open ( " output . txt " , " w " ) as file :
3 file . writelines ( lines )
2
Python Lab Manual File Handling
6. Other Useful File Methods
• file.tell(): Returns current file position.
• file.seek(offset, whence): Moves file pointer.
• file.flush(): Flushes internal buffer.
Example using seek() and tell():
1 with open ( " example . txt " , " r " ) as file :
2 print ( file . tell () ) # Position ( should be 0)
3 print ( file . read (5) ) # Read first 5 characters
4 print ( file . tell () ) # Position after reading 5 chars
5 file . seek (0) # Move pointer to start
6 print ( file . read (5) ) # Read again first 5 chars
7. Exception Handling with Files
When working with files, exceptions like FileNotFoundError or IOError can occur. Use
try-except blocks to handle such errors gracefully.
1 try :
2 with open ( " nonexistent . txt " , " r " ) as file :
3 content = file . read ()
4 print ( content )
5 except Fil eNotFo undEr ror :
6 print ( " Error : The file does not exist . " )
7 except IOError :
8 print ( " Error : An I / O error occurred . " )
You can also use finally to execute code regardless of errors (e.g., closing files if not using
with):
1 file = None
2 try :
3 file = open ( " example . txt " , " r " )
4 print ( file . read () )
5 except Fil eNotFo undEr ror :
6 print ( " File not found . " )
7 finally :
8 if file :
9 file . close ()
8. Activities
Activity 1: Read and Print File Content
Create a text file named "sample.txt" with some text in it. Write a Python program to
read and print its entire content.
3
Python Lab Manual File Handling
Activity 2: Write User Input to a File
Write a program that asks the user to input 3 lines of text and writes them into "user input.txt".
Activity 3: Append Text to Existing File
Append the text ”This is an appended line.” to "user input.txt" without overwriting
the existing content.
Activity 4: Read File Line by Line
Write a program to read "sample.txt" line by line and print each line with its line number.
Activity 5: File Pointer Position
Write a program to open "sample.txt", read the first 10 characters, then print the current
position of the file pointer, seek to the start, and read the first 10 characters again.
Activity 6: Exception Handling
Write a program to safely open and read from a file named "data.txt". If the file does not
exist, print an error message without the program crashing.