Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
Quick Tips
- • Import random module for number generation
- • Use randint(1, 6) for dice simulation
- • Handle user input validation properly
TEXT FILES IN PYTHON - Copying lines to a new file & Replacing the '-' sign with a blankspace
AIM
To write a Python program to copy lines from one text file to another and replace all '-' signs with blank spaces.
ALGORITHM
- Start
- Open the source file in read mode
- Open the destination file in write mode
- Read each line from the source file
- Replace all '-' characters with blank spaces in each line
- Write the modified line to the destination file
- Close both files
- Display success message
- Stop
PROGRAM
# Python program to copy lines from one file to another
# and replace '-' with blank spaces
def copy_and_replace():
try:
# Open source file in read mode
with open('source.txt', 'r') as source_file:
# Open destination file in write mode
with open('destination.txt', 'w') as dest_file:
# Read each line from source file
for line in source_file:
# Replace '-' with blank space
modified_line = line.replace('-', ' ')
# Write modified line to destination file
dest_file.write(modified_line)
print("File copied successfully!")
print("All '-' signs replaced with blank spaces.")
except FileNotFoundError:
print("Error: Source file not found!")
except Exception as e:
print(f"Error: {e}")
def create_sample_file():
"""Create a sample source file for demonstration"""
sample_content = """Python-is-a-programming-language
Data-structures-are-important
File-handling-in-Python
Text-processing-operations
String-manipulation-techniques"""
with open('source.txt', 'w') as file:
file.write(sample_content)
print("Sample source file created!")
def display_files():
"""Display contents of both files"""
print("\n--- Source File Content ---")
try:
with open('source.txt', 'r') as file:
print(file.read())
except FileNotFoundError:
print("Source file not found!")
print("\n--- Destination File Content ---")
try:
with open('destination.txt', 'r') as file:
print(file.read())
except FileNotFoundError:
print("Destination file not found!")
# Main program
if __name__ == "__main__":
print("TEXT FILE OPERATIONS - Copy and Replace")
print("=" * 40)
# Create sample file
create_sample_file()
# Copy and replace
copy_and_replace()
# Display both files
display_files()OUTPUT
TEXT FILE OPERATIONS - Copy and Replace
========================================
Sample source file created!
File copied successfully!
All '-' signs replaced with blank spaces.
--- Source File Content ---
Python-is-a-programming-language
Data-structures-are-important
File-handling-in-Python
Text-processing-operations
String-manipulation-techniques
--- Destination File Content ---
Python is a programming language
Data structures are important
File handling in Python
Text processing operations
String manipulation techniques
CONCLUSION
The program successfully demonstrates file handling operations in Python. It reads content from a source file, processes each line by replacing '-' characters with blank spaces, and writes the modified content to a destination file. The program includes proper error handling for file operations.
VIVA QUESTIONS
What is the difference between 'r' and 'w' file modes?
'r' mode opens file for reading only, while 'w' mode opens file for writing (overwrites existing content).
What is the purpose of the replace() method?
The replace() method returns a string where all occurrences of a substring are replaced with another substring.
Why do we use 'with' statement for file operations?
The 'with' statement ensures proper file closure even if an error occurs, providing automatic resource management.
What happens if the source file doesn't exist?
A FileNotFoundError exception is raised, which should be handled using try-except blocks.
How can you append to a file instead of overwriting?
Use 'a' mode (append mode) instead of 'w' mode to add content to the end of an existing file.