Day31 to Day40 python practice questions
Index: Click to Navigate:
Day31
Day-31
Question:
Write a program that takes a file name as input, checks if the file exists, and prints its contents if it does. If not, create the file and write a default message.
Solution:
import os
file_name = input("Enter the file name: ")
if os.path.exists(file_name):
print("\nFile exists! Printing contents:\n")
with open(file_name, "r") as file:
print(file.read())
else:
print("\nFile does not exist. Creating file with a default message...\n")
with open(file_name, "w") as file:
file.write("Hello! This is a default message.\n")
print(f"File '{file_name}' created successfully with default content.")
Output:
Case 1: File Already Exists
Input:
Enter the file name: example.txt
Output :(example.txt
contains "Welcome to Pythonbuzz!"
)
File exists! Printing contents:
Welcome to Pythonbuzz!
Case 2: File Does Not Exist
Input:
Enter the file name: newfile.txt
Output:
File does not exist. Creating file with a default message...
File 'newfile.txt' created successfully with default content.
Now, newfile.txt
is created with this content:
Hello! This is a default message.
1️⃣ Importing the Required Module
import os
- The
os
module provides operating system-related functionalities, including file handling.
import os
os
module provides operating system-related functionalities, including file handling.2️⃣ Taking File Name as Input
file_name = input("Enter the file name: ")
input()
asks the user to enter a file name.
- The entered file name is stored in the variable
file_name
.
file_name = input("Enter the file name: ")
input()
asks the user to enter a file name.file_name
.Example:
Enter the file name: myfile.txt
3️⃣ Checking If the File Exists
if os.path.exists(file_name):
os.path.exists(file_name)
checks if the file already exists in the current directory.
- If the file exists, it will print its contents; otherwise, it will create the file.
if os.path.exists(file_name):
os.path.exists(file_name)
checks if the file already exists in the current directory.4️⃣ If the File Exists: Read and Print Contents
print("\nFile exists! Printing contents:\n")
with open(file_name, "r") as file:
print(file.read())
- If the file already exists, it:
- Prints
"File exists! Printing contents:"
- Opens the file in read mode (
"r"
).
- Reads and prints the contents of the file.
print("\nFile exists! Printing contents:\n")
with open(file_name, "r") as file:
print(file.read())
- Prints
"File exists! Printing contents:"
- Opens the file in read mode (
"r"
). - Reads and prints the contents of the file.
Example (if myfile.txt
exists and contains "Python is fun!"
):
File exists! Printing contents:
Python is fun!
5️⃣ If the File Does Not Exist: Create It with Default Content
else:
print("\nFile does not exist.Creating file with a default message...\n")
with open(file_name, "w") as file:
file.write("Hello! This is a default message.\n")
print(f"File '{file_name}' created successfully with default content.")
- If the file does NOT exist, it:
- Prints
"File does not exist. Creating file with a default message..."
.
- Opens the file in write mode (
"w"
).
- Writes
"Hello! This is a default message."
inside the file.
- Prints confirmation that the file was created.
else:
print("\nFile does not exist.Creating file with a default message...\n")
with open(file_name, "w") as file:
file.write("Hello! This is a default message.\n")
print(f"File '{file_name}' created successfully with default content.")
- Prints
"File does not exist. Creating file with a default message..."
. - Opens the file in write mode (
"w"
). - Writes
"Hello! This is a default message."
inside the file. - Prints confirmation that the file was created.
Example (if myfile.txt
does not exist):
File does not exist. Creating file with a default message...
File 'myfile.txt' created successfully with default content.
Now, myfile.txt
will be created with this content:
Hello! This is a default message.
Question:
Write a program that logs timestamps into a file every time the script runs.
Timestamp 2025-02-24 11:30:45 logged successfully in 'timestamps.log'.
Second Run Output (Terminal):
Timestamp 2025-02-24 11:31:10 logged successfully in 'timestamps.log'.
Content of timestamps.log
after multiple runs:
logged at: 2025-02-24 11:30:45
logged at: 2025-02-24 11:31:10
logged at: 2025-02-24 11:32:05
from datetime import datetime
- The
datetime
module provides date and time functionalities. datetime.now()
fetches the current date and time.
2️⃣ Define the Log File Name
log_file = "timestamps.log"
log_file
is the file where timestamps will be saved.- If
timestamps.log
does not exist, Python will create it automatically.
3️⃣ Get the Current Timestamp
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
datetime.now()
fetches the current system date and time..strftime("%Y-%m-%d %H:%M:%S")
formats it into:
Example output:YYYY-MM-DD HH:MM:SS
2025-02-24 11:30:45
4️⃣ Open the File in Append Mode and Write the Timestamp
with open(log_file, "a") as file:
file.write("logged at: " + current_time + "\n")
open(log_file, "a")
→ Opens the file in append mode ("a"
).- This ensures new timestamps are added without deleting previous ones.
file.write("logged at: " + current_time + "\n")
- Writes
"logged at: YYYY-MM-DD HH:MM:SS"
inside the file. "\n"
moves to the next line for the next entry.
- Writes
5️⃣ Print Confirmation Message
print(f"Timestamp {current_time} logged successfully in '{log_file}'.")
- Displays a confirmation message that the timestamp was saved.
Day-33
Question:
Write a program that asks for a file name, tries to open it, and prints its content. If the file does not exist, catch the FileNotFoundError
and display a user-friendly message.
🔹 Example Runs:
✅ Case 1: File Exists
Enter the file name: sample.txt
File found! Printing contents:
Hello, this is a sample text file.
❌ Case 2: File Not Found
Enter the file name: unknown.txt
❌ Error: The file does not exist.
Please check the file name and try again.
Explanation:
1️⃣ Ask for File Name:
✅ Case 1: File Exists
Enter the file name: sample.txt
File found! Printing contents:
Hello, this is a sample text file.
❌ Case 2: File Not Found
Enter the file name: unknown.txt
❌ Error: The file does not exist.
Please check the file name and try again.
Explanation:
1️⃣ Ask for File Name:
file_name = input("Enter the file name: ")
- The program prompts the user to enter the name of a file they want to open.
- The input is stored in the variable
file_name
.
2️⃣ Try to Open the File:
try:
with open(file_name, "r") as file:
print("\nFile found! Printing contents:\n")
print(file.read())
- The program attempts to open the file in read mode (
"r"
) inside a try
block.
- If the file exists:
- It reads the file’s contents using
.read()
.
- The content is printed on the screen.
3️⃣ Handle File Not Found Error:
except FileNotFoundError:
print("\n Error: The file does not exist. Please check the file n
ame and try again.")
- If the file does not exist, Python raises a
FileNotFoundError
.
- The
except
block catches this error and prints a friendly error message instead of letting the program crash.
file_name = input("Enter the file name: ")
file_name
.try:
with open(file_name, "r") as file:
print("\nFile found! Printing contents:\n")
print(file.read())
"r"
) inside a try
block.- It reads the file’s contents using
.read()
. - The content is printed on the screen.
except FileNotFoundError:
print("\n Error: The file does not exist. Please check the file n
ame and try again.")
FileNotFoundError
.except
block catches this error and prints a friendly error message instead of letting the program crash.📌 Why Use try-except
?
- Without
try-except
: If the file doesn’t exist, Python will show a long error traceback and stop execution.
- With
try-except
: The program handles the error gracefully and gives a clear message to the user.
try-except
: If the file doesn’t exist, Python will show a long error traceback and stop execution.try-except
: The program handles the error gracefully and gives a clear message to the user.Day-34
Question:
Write a program that asks the user for a file name to delete. If the file exists, delete it after user confirmation. Handle FileNotFoundError and PermissionError if deletion fails.
Solution:
import os
file_name = input("Enter the file name to delete: ")
try:
if os.path.exists(file_name):
confirmation = input(f"Are you sure you want to delete '{file_name}'? (yes/no): ").strip().lower()
if confirmation == "yes":
os.remove(file_name)
print(f"\nFile '{file_name}' has been deleted successfully.")
else:
print("\nFile deletion canceled.")
else:
raise FileNotFoundError
except FileNotFoundError:
print("\nError: The file does not exist. Please check the file name and try again.")
except PermissionError:
print("\nError: You don't have permission to delete this file.")
Output:
Example Runs:
Question:
Write a program that asks the user for a file name to delete. If the file exists, delete it after user confirmation. Handle FileNotFoundError and PermissionError if deletion fails.
Solution:
import os
file_name = input("Enter the file name to delete: ")
try:
if os.path.exists(file_name):
confirmation = input(f"Are you sure you want to delete '{file_name}'? (yes/no): ").strip().lower()
if confirmation == "yes":
os.remove(file_name)
print(f"\nFile '{file_name}' has been deleted successfully.")
else:
print("\nFile deletion canceled.")
else:
raise FileNotFoundError
except FileNotFoundError:
print("\nError: The file does not exist. Please check the file name and try again.")
except PermissionError:
print("\nError: You don't have permission to delete this file.")
✅ Case 1: File Exists & User Confirms Deletion
✅ Case 2: File Exists & User Cancels Deletion
❌ Case 3: File Not Found
❌ Case 4: Permission Denied
📌 Error Handling:
Day-35
Question:
Write a program to search for a specific word in a file and print its line number(s).
Solution:
file_name = input("Enter the file name: ")
search_word = input("Enter the word to search: ")
try:
with open(file_name, "r") as file:
found = False
for line_num, line in enumerate(file, start=1):
if search_word in line:
print(f"Found '{search_word}' on line {line_num}")
found = True
if not found:
print(f"'{search_word}' not found in the file.")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
Output:
Question:
Write a program to search for a specific word in a file and print its line number(s).
Solution:
file_name = input("Enter the file name: ")
search_word = input("Enter the word to search: ")
try:
with open(file_name, "r") as file:
found = False
for line_num, line in enumerate(file, start=1):
if search_word in line:
print(f"Found '{search_word}' on line {line_num}")
found = True
if not found:
print(f"'{search_word}' not found in the file.")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
Output:
Example Run:
📂 Sample File (data.txt
)
Python is amazing.
I love programming in Python.
File handling is important in Python.
Python is amazing.
I love programming in Python.
File handling is important in Python.
👨💻 User Input & Output
Enter the file name: data.txt
Enter the word to search: Python
Found 'Python' on line 1
Found 'Python' on line 2
Found 'Python' on line 3
Enter the file name: data.txt
Enter the word to search: Python
Found 'Python' on line 1
Found 'Python' on line 2
Found 'Python' on line 3
📌 If Word is Not Found:
Enter the file name: data.txt
Enter the word to search: Java
'Java' not found in the file.
Enter the file name: data.txt
Enter the word to search: Java
'Java' not found in the file.
🚨 If File Does Not Exist:
Enter the file name: missing.txt
Error: File not found. Please check the file name.
Enter the file name: missing.txt
Error: File not found. Please check the file name.
Explanation:
-
Take user input:
file_name
: Name of the file to search in.
search_word
: Word to search for in the file.
-
Try-Except Block for Error Handling:
FileNotFoundError
is handled if the file doesn’t exist.
-
Open and Read the File:
- The file is opened in read mode (
"r"
).
- The program iterates through each line, using
enumerate(file, start=1)
to track line numbers.
-
Search for the Word:
- If
search_word
is found in a line, the program prints the line number.
- A flag variable (
found
) is set to True
if the word exists.
-
Display a Message If the Word is Not Found:
- If
found
remains False
, a message is printed that the word was not found.
Take user input:
file_name
: Name of the file to search in.search_word
: Word to search for in the file.
Try-Except Block for Error Handling:
FileNotFoundError
is handled if the file doesn’t exist.
Open and Read the File:
- The file is opened in read mode (
"r"
). - The program iterates through each line, using
enumerate(file, start=1)
to track line numbers.
Search for the Word:
- If
search_word
is found in a line, the program prints the line number. - A flag variable (
found
) is set toTrue
if the word exists.
Display a Message If the Word is Not Found:
- If
found
remainsFalse
, a message is printed that the word was not found.
Day-36
Question:
Write a program to replace a specific word in a file with another word.
Solution:
file_name = input("Enter the file name: ")
old_word = input("Enter the word to replace: ")
new_word = input("Enter the new word: ")
try:
with open(file_name, "r") as file:
content = file.read()
new_content = content.replace(old_word, new_word)
with open(file_name, "w") as file:
file.write(new_content)
print(f"All occurrences of '{old_word}' replaced with '{new_word}' successfully.")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
Output:
Question:
Write a program to replace a specific word in a file with another word.
Solution:
file_name = input("Enter the file name: ")
old_word = input("Enter the word to replace: ")
new_word = input("Enter the new word: ")
try:
with open(file_name, "r") as file:
content = file.read()
new_content = content.replace(old_word, new_word)
with open(file_name, "w") as file:
file.write(new_content)
print(f"All occurrences of '{old_word}' replaced with '{new_word}' successfully.")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
🔹 Example Run
📂 Sample File (data.txt
)
Python is amazing.
I love programming in Python.
File handling is important in Python.
Python is amazing.
I love programming in Python.
File handling is important in Python.
👨💻 User Input & Output
Enter the file name: data.txt
Enter the word to replace: Python
Enter the new word: Java
All occurrences of 'Python' replaced with 'Java' successfully.
Enter the file name: data.txt
Enter the word to replace: Python
Enter the new word: Java
All occurrences of 'Python' replaced with 'Java' successfully.
📂 Updated data.txt
Java is amazing.
I love programming in Java.
File handling is important in Java.
Java is amazing.
I love programming in Java.
File handling is important in Java.
Explanation:
-
Take User Input:
file_name
: Name of the file to modify.
old_word
: Word to be replaced.
new_word
: New word to replace it with.
-
Try-Except Block for Error Handling:
- Handles
FileNotFoundError
if the file doesn’t exist.
-
Read the File:
- The file is opened in read mode (
"r"
), and its contents are stored in the variable content
.
-
Replace the Word:
- The
.replace(old_word, new_word)
method is used to modify the text.
-
Write the Updated Content Back to the File:
- The file is opened in write mode (
"w"
), and the modified content is written back.
-
Confirmation Message:
- The program confirms that all occurrences of
old_word
have been replaced.
Take User Input:
file_name
: Name of the file to modify.old_word
: Word to be replaced.new_word
: New word to replace it with.
Try-Except Block for Error Handling:
- Handles
FileNotFoundError
if the file doesn’t exist.
Read the File:
- The file is opened in read mode (
"r"
), and its contents are stored in the variablecontent
.
Replace the Word:
- The
.replace(old_word, new_word)
method is used to modify the text.
Write the Updated Content Back to the File:
- The file is opened in write mode (
"w"
), and the modified content is written back.
Confirmation Message:
- The program confirms that all occurrences of
old_word
have been replaced.
🔹 Error Handling
🚨 If File Doesn’t Exist
Enter the file name: missing.txt
Error: File not found. Please check the file name.
Enter the file name: missing.txt
Error: File not found. Please check the file name.
Day-37
Question:
Write a program that creates a backup of a file before modifying it.
Solution:
import shutil
import os
file_name = input("Enter the file name: ")
backup_location = input("Enter the backup location (leave empty for current folder): ")
if backup_location:
os.makedirs(backup_location, exist_ok=True)
backup_name = os.path.join(backup_location, "file_backup.txt")
else:
backup_name = "file_backup.txt" # Default to current folder
try:
shutil.copy(file_name, backup_name)
print(f"Backup created at '{backup_name}'.")
with open(file_name, "r") as file:
content = file.read()
modified_content = content.upper()
with open(file_name, "w") as file:
file.write(modified_content)
print("File modified successfully!")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
except PermissionError:
print("Error: You don’t have permission to modify this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output:
Question:
Write a program that creates a backup of a file before modifying it.
Solution:
import shutil
import os
file_name = input("Enter the file name: ")
backup_location = input("Enter the backup location (leave empty for current folder): ")
if backup_location:
os.makedirs(backup_location, exist_ok=True)
backup_name = os.path.join(backup_location, "file_backup.txt")
else:
backup_name = "file_backup.txt" # Default to current folder
try:
shutil.copy(file_name, backup_name)
print(f"Backup created at '{backup_name}'.")
with open(file_name, "r") as file:
content = file.read()
modified_content = content.upper()
with open(file_name, "w") as file:
file.write(modified_content)
print("File modified successfully!")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
except PermissionError:
print("Error: You don’t have permission to modify this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output:
Case 1: Valid file and backup location
Enter the file name: test1.txt
Enter the backup location (leave empty for current folder): D:\Backups
Backup created at 'D:\Backups\file_backup.txt'.
File modified successfully!
Enter the file name: test1.txt
Enter the backup location (leave empty for current folder): D:\Backups
Backup created at 'D:\Backups\file_backup.txt'.
File modified successfully!
Case 2: User leaves backup location empty (saves in current folder)
Enter the file name: test1.txt
Enter the backup location (leave empty for current folder):
Backup created at 'file_backup.txt'.
File modified successfully!
Enter the file name: test1.txt
Enter the backup location (leave empty for current folder):
Backup created at 'file_backup.txt'.
File modified successfully!
Case 3: File not found
Enter the file name: non_existent.txt
Enter the backup location (leave empty for current folder): D:\Backups
Error: File not found. Please check the file name.
Enter the file name: non_existent.txt
Enter the backup location (leave empty for current folder): D:\Backups
Error: File not found. Please check the file name.
Case 4: No permission to modify file
Enter the file name: C:\System32\config.sys
Enter the backup location (leave empty for current folder): D:\Backups
Error: You don’t have permission to modify this file.
Enter the file name: C:\System32\config.sys
Enter the backup location (leave empty for current folder): D:\Backups
Error: You don’t have permission to modify this file.
Explanation:
1️⃣ Take Input
file_name = input("Enter the file name: ")
backup_location = input("Enter the backup location (leave empty for current
folder): ")
- User enters the file name and optionally a backup location.
2️⃣ Create Backup Directory (if needed)
if backup_location:
os.makedirs(backup_location, exist_ok=True)
backup_name = os.path.join(backup_location, "file_backup.txt")
else:
backup_name = "file_backup.txt" # Default to current folder
- If the backup location is provided, it creates the directory (if it doesn't exist).
- If the user leaves it empty, backup is saved in the current folder.
3️⃣ Copy File for Backup
shutil.copy(file_name, backup_name)
print(f"Backup created at '{backup_name}'.")
shutil.copy()
copies the file to the backup location.
4️⃣ Read and Modify File Content
with open(file_name, "r") as file:
content = file.read()
modified_content = content.upper()
with open(file_name, "w") as file:
file.write(modified_content)
- Reads the original file.
- Modifies its content (in this case, converts text to uppercase).
- Writes the modified content back to the original file.
5️⃣ Error Handling
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
except PermissionError:
print("Error: You don’t have permission to modify this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
- FileNotFoundError → If the file doesn’t exist.
- PermissionError → If the file is protected/system file.
- General Exception → Handles unexpected issues.
Day-38
Question:
Write a program that asks the user for two file names and merges their contents into a new file.
Solution:
file1 = input("Enter the first file name: ")
file2 = input("Enter the second file name: ")
output_file = "merged_file.txt"
try:
with open(file1, "r") as f1, open(file2, "r") as f2, open(output_file, "w") as out:
out.write(f1.read() + "\n")
out.write(f2.read())
print(f"Files merged successfully into '{output_file}'.")
except FileNotFoundError:
print("Error: One or both files not found. Please check the file names.")
except PermissionError:
print("Error: You don’t have permission to access one of the files.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output:
Question:
Write a program that asks the user for two file names and merges their contents into a new file.Solution:
file1 = input("Enter the first file name: ")
file2 = input("Enter the second file name: ")
output_file = "merged_file.txt"
try:
with open(file1, "r") as f1, open(file2, "r") as f2, open(output_file, "w") as out:
out.write(f1.read() + "\n")
out.write(f2.read())
print(f"Files merged successfully into '{output_file}'.")
except FileNotFoundError:
print("Error: One or both files not found. Please check the file names.")
except PermissionError:
print("Error: You don’t have permission to access one of the files.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output:
Case 1: Successful Merge
Suppose file1.txt
contains:
Hello from File 1!
This is line 2.
Hello from File 1!
This is line 2.
And file2.txt
contains:
Welcome from File 2!
This is another line.
Welcome from File 2!
This is another line.
🔹 User Input:
Enter the first file name: file1.txt
Enter the second file name: file2.txt
🔹 Output:
Files merged successfully into 'merged_file.txt'.
🔹 Content of merged_file.txt
after execution:
Hello from File 1!
This is line 2.
Welcome from File 2!
This is another line.
✅ Case 2: File Not Found Error
User Input:
Enter the first file name: file1.txt
Enter the second file name: missing_file.txt
Enter the first file name: file1.txt
Enter the second file name: missing_file.txt
🔹 Output:
Error: One or both files not found. Please check the file names.
✅ Case 3: Permission Error
(Trying to merge files that the user doesn’t have permission to access)
🔹 Output:
Error: You don’t have permission to access one of the files.
✅ Case 4: Unexpected Error
If any unknown error occurs (e.g., disk full), it prints:
An unexpected error occurred: [Error details]
Explanation:
1️⃣ Input File Names:
file1 = input("Enter the first file name: ")
file2 = input("Enter the second file name: ")
- The program asks the user to enter the names of two files.
- These file names are stored in
file1
andfile2
variables.
2️⃣ Define Output File Name:
output_file = "merged_file.txt"
- The merged content will be saved in
merged_file.txt
.
3️⃣ Try Block to Handle Exceptions:
try:
with open(file1, "r") as f1, open(file2, "r") as f2, open(output_file, "w")
as out:
out.write(f1.read() + "\n")
out.write(f2.read())
- The
with
statement is used to open multiple files at once. - The first two files are opened in read mode (
"r"
). - The third file (
merged_file.txt
) is opened in write mode ("w"
). - The content of the first file is read and written into the new file, followed by a newline (
\n
). - Then the content of the second file is appended to the new file.
4️⃣ Success Message:
print(f"Files merged successfully into '{output_file}'.")
- If no errors occur, the program prints a success message.
5️⃣ Exception Handling:
- If the file is not found:
except FileNotFoundError:
print("Error: One or both files not found. Please check the file names.")
- If the user doesn’t have permission to access the file:
except PermissionError:
print("Error: You don’t have permission to access one of the files.")
- If any other unexpected error occurs:
except Exception as e:
print(f"An unexpected error occurred: {e}")
Day-39
Question:
Write a Python program that adds line numbers to each line in a file.
Requirements:
- Read the file.
- Add line numbers at the beginning of each line.
- Save the changes back to the file.
- Handle errors like file not found and permission issues.
📌 Hint: Use enumerate()
to number the lines.
Solution:
file_name = input("Enter the file name: ")
try:
with open(file_name, "r") as file:
lines = file.readlines()
numbered_lines = [f"{i+1}-{line}" for i, line in enumerate(lines)]
with open(file_name, "w") as file:
file.writelines(numbered_lines)
print("Line numbers added successfully!")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
except PermissionError:
print("Error: You don’t have permission to modify this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output:
Question:
Write a Python program that adds line numbers to each line in a file.
Requirements:
- Read the file.
- Add line numbers at the beginning of each line.
- Save the changes back to the file.
- Handle errors like file not found and permission issues.
📌 Hint: Use enumerate()
to number the lines.
Solution:
file_name = input("Enter the file name: ")
try:
with open(file_name, "r") as file:
lines = file.readlines()
numbered_lines = [f"{i+1}-{line}" for i, line in enumerate(lines)]
with open(file_name, "w") as file:
file.writelines(numbered_lines)
print("Line numbers added successfully!")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
except PermissionError:
print("Error: You don’t have permission to modify this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output:
Scenario 1: Normal Execution
Input (sample.txt
before execution)
Hello, this is the first line.
This is the second line.
Python is amazing!
Hello, this is the first line.
This is the second line.
Python is amazing!
UserInput
Enter the file name: sample.txt
Enter the file name: sample.txt
Output
Line numbers added successfully!
Line numbers added successfully!
Updated File (sample.txt
after execution)
1-Hello, this is the first line.
2-This is the second line.
3-Python is amazing!
1-Hello, this is the first line.
2-This is the second line.
3-Python is amazing!
Scenario 2: File Not Found
User Input
Enter the file name: missing_file.txt
Enter the file name: missing_file.txt
Output
Error: File not found. Please check the file name.
Error: File not found. Please check the file name.
Scenario 3: Permission Error
Possible Causes
- Trying to modify a read-only file.
- Trying to modify a system-protected file.
User Input
Enter the file name: C:\Windows\System32\config.sys
Enter the file name: C:\Windows\System32\config.sys
Output
Error: You don’t have permission to modify this file.
Error: You don’t have permission to modify this file.
Scenario 4: Unexpected Error
If an unexpected issue occurs (e.g., corrupted file, disk error), the program will print:
An unexpected error occurred: [Error details]
Explanation:
file_name = input("Enter the file name: ")
- The program prompts the user to enter the file name.
- The input file should exist in the same directory as the script (or the full path should be provided).
Step 1: Read the File Content
with open(file_name, "r") as file:
lines = file.readlines()
- Opens the file in read mode ("r").
- Reads all lines from the file and stores them as a list in
lines
.
Step 2: Add Line Numbers
numbered_lines = [f"{i+1}-{line}" for i, line in enumerate(lines)]
- Uses list comprehension with
enumerate()
to iterate overlines
while keeping track of the line number (i
). i+1
ensures numbering starts from 1 instead of 0.- Each line is formatted as
"1-<line content>"
,"2-<line content>"
, etc.
Step 3: Write Modified Content Back to the File
with open(file_name, "w") as file:
file.writelines(numbered_lines)
- Opens the file in write mode ("w"), which overwrites the existing content.
- Writes the modified list (
numbered_lines
) back to the file.
Error Handling
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
- If the file does not exist, the program catches the
FileNotFoundError
and informs the user.
except PermissionError:
print("Error: You don’t have permission to modify this file.")
- If the file is read-only or located in a restricted system folder, this error occurs.
except Exception as e:
print(f"An unexpected error occurred: {e}")
- Catches any other errors (e.g., disk issues, encoding errors) and prints the error message.
Question:
Delete Specific Lines from a File
Ask the user for a file name and a line number. Remove that line from the file.
Solution:
try:
file_name = input("Enter the file name: ").strip()
line_number = int(input("Enter the line number to delete: "))
with open(file_name, "r") as file:
lines = file.readlines()
if line_number < 1 or line_number > len(lines):
print("Error: Invalid line number. Please enter a valid line number.")
else:
del lines[line_number - 1]
with open(file_name, "w") as file:
file.writelines(lines)
print("Line deleted successfully!")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
except ValueError:
print("Error: Invalid input. Please enter a valid line number.")
except PermissionError:
print("Error: You don’t have permission to modify this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output:
Question:
Delete Specific Lines from a File Ask the user for a file name and a line number. Remove that line from the file.Solution:
try:
file_name = input("Enter the file name: ").strip()
line_number = int(input("Enter the line number to delete: "))
with open(file_name, "r") as file:
lines = file.readlines()
if line_number < 1 or line_number > len(lines):
print("Error: Invalid line number. Please enter a valid line number.")
else:
del lines[line_number - 1]
with open(file_name, "w") as file:
file.writelines(lines)
print("Line deleted successfully!")
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
except ValueError:
print("Error: Invalid input. Please enter a valid line number.")
except PermissionError:
print("Error: You don’t have permission to modify this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Scenario 1: Successful Deletion
File Content (sample.txt
) Before Execution:
Line 1: Hello World
Line 2: Python is fun
Line 3: This is a test file
Line 4: Deleting a line
User Input:
Enter the file name: sample.txt
Enter the line number to delete: 3
Output:
Line deleted successfully!
File Content After Execution (sample.txt
):
Line 1: Hello World
Line 2: Python is fun
Line 3: Deleting a line
(Line 3 is removed, and the remaining lines shift up.)
Scenario 2: File Not Found
User Input:
Enter the file name: nonexistent.txt
Enter the line number to delete: 2
Output:
Error: File not found. Please check the file name.
Scenario 3: Invalid Line Number (Too High or Negative)
File Content (sample.txt
) Before Execution:
Line 1: Hello World
Line 2: Python is fun
Line 3: This is a test file
User Input:
Enter the file name: sample.txt
Enter the line number to delete: 5
Output:
Error: Invalid line number. Please enter a valid line number.
(Since the file only has 3 lines, line 5 does not exist.)
User Input:
Enter the file name: sample.txt
Enter the line number to delete: -1
Output:
Error: Invalid line number. Please enter a valid line number.
(Line numbers must be positive.)
Scenario 4: Invalid Input (Non-Numeric Line Number)
User Input:
Enter the file name: sample.txt
Enter the line number to delete: hello
Output:
Error: Invalid input. Please enter a valid line number.
(The user entered text instead of a number.)
Scenario 5: Permission Denied
User Input (Trying to modify a read-only file):
Enter the file name: protected.txt
Enter the line number to delete: 2
Output:
Error: You don’t have permission to modify this file.
(This happens when the file is read-only or requires admin access.)
Explanation:
1. Taking User Input
file_name = input("Enter the file name: ").strip()
line_number = int(input("Enter the line number to delete: "))
- The program prompts the user to enter the file name and the line number.
.strip()
is used to remove any extra spaces before or after the file name.
int(input())
ensures the line number is treated as an integer.
file_name = input("Enter the file name: ").strip()
line_number = int(input("Enter the line number to delete: "))
.strip()
is used to remove any extra spaces before or after the file name.int(input())
ensures the line number is treated as an integer.2. Opening the File and Reading Lines
with open(file_name, "r") as file:
lines = file.readlines()
- The file is opened in read mode (
"r"
).
readlines()
reads all lines from the file into a list called lines
, where each element represents a line.
with open(file_name, "r") as file:
lines = file.readlines()
"r"
).readlines()
reads all lines from the file into a list called lines
, where each element represents a line.3. Validating the Line Number
if line_number < 1 or line_number > len(lines):
print("Error: Invalid line number. Please enter a valid line number.")
- Checks if the entered
line_number
is out of range.
- If
line_number
is less than 1 (negative or zero) or greater than the number of lines, an error message is displayed.
if line_number < 1 or line_number > len(lines):
print("Error: Invalid line number. Please enter a valid line number.")
line_number
is out of range.line_number
is less than 1 (negative or zero) or greater than the number of lines, an error message is displayed.4. Deleting the Specified Line
del lines[line_number - 1]
- If the line number is valid,
del
removes the corresponding line from the lines
list.
- Since Python uses zero-based indexing, we subtract 1 to get the correct index.
del lines[line_number - 1]
del
removes the corresponding line from the lines
list.5. Writing the Updated Content Back to the File
with open(file_name, "w") as file:
file.writelines(lines)
- Opens the file in write mode (
"w"
), which overwrites the existing content.
writelines(lines)
writes the modified list back to the file.
with open(file_name, "w") as file:
file.writelines(lines)
"w"
), which overwrites the existing content.writelines(lines)
writes the modified list back to the file.6. Printing Success Message
print("Line deleted successfully!")
- If everything runs smoothly, it prints a success message.
print("Line deleted successfully!")
Exception Handling
This program includes error handling to manage different types of errors:
1. FileNotFoundError
– File Does Not Exist
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
- Occurs if the file name provided by the user does not exist.
except FileNotFoundError:
print("Error: File not found. Please check the file name.")
2. ValueError
– Invalid Input for Line Number
except ValueError:
print("Error: Invalid input. Please enter a valid line number.")
- Raised if the user enters non-numeric input instead of an integer (e.g.,
"abc"
instead of 3
).
except ValueError:
print("Error: Invalid input. Please enter a valid line number.")
"abc"
instead of 3
).3. PermissionError
– No Permission to Modify the File
except PermissionError:
print("Error: You don’t have permission to modify this file.")
- Raised if the file is read-only or requires admin privileges to modify.
except PermissionError:
print("Error: You don’t have permission to modify this file.")
4. Exception
– Catch-All for Unexpected Errors
except Exception as e:
print(f"An unexpected error occurred: {e}")
- This handles any other errors that were not anticipated.
except Exception as e:
print(f"An unexpected error occurred: {e}")
Comments
Post a Comment