Cycle 03
Lab Cycle 3 — File Handling & Exception Handling
Copy Alternate (Odd-Numbered) Lines from File1 to File2
Problem Statement
Write a Python function that reads a file 'file1' and copies only alternative lines to another file 'file2'. Alternative lines copied should be the odd numbered lines (1st, 3rd, 5th, etc.).
def copy_alternate_odd_lines(source_file, dest_file):
"""
Reads source_file and copies only odd-numbered lines (1, 3, 5, ...)
to dest_file using context managers.
"""
copied_count = 0
try:
with open(source_file, 'r') as fin, open(dest_file, 'w') as fout:
for line_number, line in enumerate(fin, start=1):
if line_number % 2 != 0: # Odd numbered line
fout.write(line)
copied_count += 1
print(f"Successfully copied {copied_count} odd-numbered lines to '{dest_file}'.")
except FileNotFoundError:
print(f"Error: Source file '{source_file}' not found!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
def create_sample_file(filename):
with open(filename, 'w') as f:
f.write("Line 1: Python programming basics\n")
f.write("Line 2: Data Structures and Algorithms\n")
f.write("Line 3: Database Management Systems\n")
f.write("Line 4: Computer Networks\n")
f.write("Line 5: Artificial Intelligence\n")
f.write("Line 6: Operating Systems\n")
def main():
src = "file1.txt"
dest = "file2.txt"
# Create sample file for demonstration
create_sample_file(src)
# Execute copy function
copy_alternate_odd_lines(src, dest)
# Display destination file contents
print("\n--- Contents of file2.txt (Odd Lines) ---")
with open(dest, 'r') as f:
print(f.read(), end="")
if __name__ == "__main__":
main()
Question 1 of 3