Python Program on File I/O
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
In the vast landscape of Python programming, the ability to seamlessly read and write data in files constitutes a fundamental skill for any developer. This process not only enables the preservation and retrieval of information between program runs but also forms the backbone of various applications, from data storage to configuration management.
Mastering Python’s File I/O (Input/Output) capabilities is a practical and essential aspect of programming, and in this tutorial, we’ll embark on a hands-on exploration of the methods and practices involved in reading and writing data to files, offering a comprehensive guide to enhance your proficiency in Python’s File I/O operations.
Topic Explanation:
This tutorial explores the practical side of working with files in Python, specifically how to read and write data. We’ll start by breaking down the basics of opening files for reading and writing, helping you effectively manage the content within them.
Our exploration will extend to methods for reading data from files, providing insights into techniques like line-by-line reading and complete file retrieval. We’ll then transition seamlessly into the art of writing data, covering diverse scenarios from creating new files to appending content to existing ones.
As we move forward, we’ll cover more advanced file-handling techniques, including strategies to handle errors and strengthen your programs against unexpected problems. We’ll also highlight Python’s versatility by demonstrating how to deal with various types of files and gracefully manage exceptions.
By the end of this tutorial, you’ll have a robust understanding of Python File I/O, capable of implementing effective data reading and writing strategies in your projects.
Prerequisites:
- Basic proficiency in Python programming, encompassing knowledge of variables, data types, and control structures.
- Familiarity with file system concepts, including directories, file paths, and file permissions.
- A functional Python interpreter installed on your machine.
- Prior exposure to basic file handling operations (optional but beneficial).
Code 1 with comments:
# Use a try-except block to handle potential exceptions
try:
# Open the file in "a" (append) mode, creating the file if it doesn't exist
f = open("c://myfile/employee.txt", "a")
# Prompt the user to enter a string for the file
str_input = input("Enter a String for file: ")
# Write the entered string to the file
f.write(str_input)
# Display the close status of the file before closing
print("Close status before closing")
print(f.closed)
# Close the file
f.close()
# Display the close status of the file after closing
print("Close status after closing")
print(f.closed)
# Catch the FileNotFoundError exception and print the corresponding error message
except FileNotFoundError as obj:
print(obj)Output for code 1:
Enter a String for file: Hello, this is a test string!
Close status before closing
False
Close status after closing
True
Code 1 Explanation:
- try:: Begins a block where potential exceptions might occur.
- f = open(“c://myfile/employee.txt”, “a”): Opens the file “employee.txt” in append mode (“a”). If the file doesn’t exist, it will be created. The file object is stored in the variable f.
str_input = input(“Enter a String for file: “): Prompts the user to enter a string for the file and stores it in the variable str_input. - f.write(str_input): Writes the entered string to the file.
- print(“Close status before closing”): Displays a message indicating that the next line will show the close status before closing.
- print(f.closed): Prints the close status of the file before closing (should be False).
- f.close(): Closes the file.
- print(“Close status after closing”): Displays a message indicating that the next line will show the close status after closing.
- print(f.closed): Prints the close status of the file after closing (should be True if closed successfully).
- except FileNotFoundError as obj:: Catches the FileNotFoundError exception, if it occurs, and stores the exception object in the variable obj.
- print(obj): Prints the error message associated with the FileNotFoundError.
Code 2 with comments:
# Use a try-except block to handle potential exceptions
try:
# Open the file in "a" (append) mode, creating the file if it doesn't exist
f = open("c://myfile/employee.txt", "a")
# Create a list containing strings to be written to the file
mylist = ["This is a class\n Data Flair Python Course\n Data flair Free Course"]
# Write the list of strings to the file
f.writelines(mylist)
# Close the file
f.close()
# Print a message indicating that the file is created
print("File created.....")
# Catch the FileNotFoundError exception and print a corresponding error message
except FileNotFoundError as obj:
print("File Not found....")Output for code 2:
File created…..
Code 2 Explanation:
- try:: Begins a block where potential exceptions might occur.
- f = open(“c://myfile/employee.txt”, “a”): Opens the file “employee.txt” in append mode (“a”). If the file doesn’t exist, it will be created. The file object is stored in the variable f.
- mylist = [“This is a class\n Data Flair Python Course\n Data flair Free Course”]: Creates a list containing strings to be written to the file. Note that the list contains a single string with newline characters.
- f.writelines(mylist): Writes the list of strings to the file. Each string in the list will be written on a new line in the file due to the newline characters.
- f.close(): Closes the file.
- print(“File created…..”): Prints a message indicating that the file is created.
Code 3 with Comments:
# Import the os and sys modules for operating system-related functionalities and system-specific parameters
import os
import sys
# Prompt the user to enter a file name for reading data
str_input = input("Enter file name for read data")
# Use a try-except block to handle potential exceptions
try:
# Check if the file exists in the specified path
if os.path.isfile("c://myfile/" + str_input + ".txt"):
# Open the file in read mode
f = open("c://myfile/" + str_input + ".txt", "r")
# Check if the file is readable
if f.readable():
# Initialize variables to count lines, words, and characters
cl = cw = cc = 0
# Read the entire content of the file
str_data = f.read()
# Print the content of the file
print(str_data)
else:
# Print a message if the file does not exist and exit the program
print("File not exists")
sys.exit()
# Catch the FileNotFoundError exception and print the corresponding error message
except FileNotFoundError as msg:
print(msg)Output For code 3:
The output of the provided code depends on the user input and the existence of the specified file. Here are a few possible scenarios:
1. File Exists and Readable:
Enter file name for read data: example
This is the content of the example.txt file.
2.File Does Not Exist:
Enter file name for read data: non_existent_file
File not exists
3.File Exists but Not Readable:
Enter file name for read data: unreadable_file
[Content of the file is not printed]
In this case, the program won’t print the content of the file because it is not readable.
4.File Not Found (Error):
Enter file name for read data: invalid_file
[FileNotFoundError message is printed].
Code 3 Explanation:
1. import os: Imports the os module, which provides a way to interact with the operating system.
2. import sys: Imports the sys module, which provides access to some variables used or maintained by the Python interpreter.
3. str_input = input(“Enter file name for read data”): Prompts the user to enter a file name for reading data and stores it in the variable str_input.
4. try:: Begins a block where potential exceptions might occur.
5. if os.path.isfile(“c://myfile/” + str_input + “.txt”):: Checks if the file exists in the specified path using os.path.isfile.
6. f = open(“c://myfile/” + str_input + “.txt”, “r”): Opens the file in read mode (“r”) and stores the file object in the variable f.
7. if f.readable():: Checks if the file is readable.
8. cl = cw = cc = 0: Initializes variables to count lines (cl), words (cw), and characters (cc).
9. str_data = f.read(): Reads the entire content of the file and stores it in the variable str_data.
10. print(str_data): Prints the content of the file.
11. else:: Executes if the file does not exist.
- print(“File not exists”): Prints a message indicating that the file does not exist.
- sys.exit(): Exits the program.
12. except FileNotFoundError as msg:: Catches the FileNotFoundError exception, if it occurs, and prints the corresponding error message.
Conclusion:
In the expansive domain of Python programming, this proficiency facilitates the persistence and retrieval of information across program executions, serving as a critical backbone for a myriad of applications, from data storage to configuration management.
Python’s File I/O capabilities, explored in this tutorial, constitute a practical and indispensable dimension of programming expertise. As the tutorial progresses, emphasis is placed on advanced file handling practices, incorporating error-handling strategies to fortify programs against unforeseen issues. This tutorial highlights Python’s versatile capabilities, showcasing how to navigate different file types and gracefully handle exceptions.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google

