HomeComputer SciencePracticalClass 12Copying Line New File

Class 12 Programs

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

  1. Start
  2. Open the source file in read mode
  3. Open the destination file in write mode
  4. Read each line from the source file
  5. Replace all '-' characters with blank spaces in each line
  6. Write the modified line to the destination file
  7. Close both files
  8. Display success message
  9. 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

  1. 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).

  2. 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.

  3. 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.

  4. What happens if the source file doesn't exist?

    A FileNotFoundError exception is raised, which should be handled using try-except blocks.

  5. 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.