Skip to content

amitpythondev/module5

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Module 5

Module 5: Files, Exceptions, and Errors in Python

Task 1: Read a File and Handle Errors

Problem Statement: Write a Python program that:

  1. Opens and reads a text file named sample.txt.
  2. Prints its content line by line.
  3. Handles errors gracefully if the file does not exist.

Code Explanation

try:
    # Attempt to open the file
    file = open("sample.txt", "r")
  • This tries to open the file named sample.txt in read mode ("r").
  • If the file doesn't exist, it raises a FileNotFoundError, which will be caught in the except block.

    print("File contents:\n")
    line_count = 1
  • This prints a header before the file content.
  • Initializes a variable line_count to keep track of line numbers while reading.

    # Read line by line
    for line in file:
        print(f"Line {line_count} : ", line.strip())
        line_count += 1
  • A loop that reads the file line by line.
  • line.strip() removes any leading/trailing whitespace (like \n).
  • print(f"Line {line_count} : ", ...) shows the current line number along with its content.
  • line_count += 1 increments the line counter after each line.

except FileNotFoundError:
    # Handle the case where the file doesn't exist
    print("Error: The file 'sample.txt' does not exist.")
  • If the file is not found, this block catches the error and prints an error message instead of crashing the program.

✅ Example Output (If File Exists):

File contents:

Line 1 :  This is a test file.
Line 2 :  It has several lines.
Line 3 :  End of file.

❌ Example Output (If File Does Not Exist):

Error: The file 'sample.txt' does not exist.

Task 2: Write and Append Data to a File

Problem Statement: Write a Python program that:

  1. Takes user input and writes it to a file named output.txt.
  2. Appends additional data to the same file.
  3. Reads and displays the final content of the file.

Code Breakdown

filename = "output.txt"
user_input = input("Enter text to write to the file : ")
  • Defines the file name as "output.txt".
  • Takes user input to write to the file initially.

output_file = open(filename, "w")
write_in_file = output_file.write(user_input + "\n")
output_file.close()
  • Opens the file in write mode ("w"), which overwrites the file if it already exists.
  • Writes the user input followed by a newline (\n) to the file.
  • Closes the file to save changes.

print("Data successfully written to ", filename)
  • Confirms that data was written.

output_file1 = open(filename, "a")
user_input1 = input("Enter text to write to the file : ")
write_in_file1 = output_file1.write(user_input1)
output_file1.close()
  • Reopens the file in append mode ("a"), which adds new content to the end without deleting previous data.
  • Takes a second user input and writes it.
  • Closes the file.

print(write_in_file1)
  • Prints the number of characters written to the file from the second input.

print("Final content of ", filename)
  • Displays the file name whose content is about to be printed.

try:
    # Attempt to open the file
    file = open(filename, "r")

    # Read line by line
    for line in file:
        print(line.strip())
  • Tries to open the file in read mode ("r").
  • Reads and prints each line with leading/trailing whitespace removed using .strip().

except FileNotFoundError:
    print("Error: The file 'output.txt' does not exist.")
  • If the file is not found, this prints an error message instead of crashing the program.

✅ Example Run

Enter text to write to the file : Hello
Data successfully written to  output.txt
Enter text to write to the file : World
5
Final content of  output.txt
Hello
World

About

Module 5: Files, Exceptions, and Errors in Python

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages