Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Implement a File Copy Context Manager | Advanced File Handling & Context Managers
Python Structural Programming
Seksjon 2. Kapittel 4
single

single

Challenge: Implement a File Copy Context Manager

Sveip for å vise menyen

Building on your knowledge of file operations and context managers, you will now implement a context manager-based solution to copy content from one file to another. This challenge reinforces the importance of managing resources safely - particularly ensuring that both the source and destination files are always closed properly, even if an error occurs during copying. You will use with statements to open and close files automatically, applying the file reading and writing techniques covered in previous chapters.

Oppgave

Sveip for å begynne å kode

Write a function named copy_file that copies the contents of one file to another using context managers with with statements.

  • The function should accept two arguments: source_path and dest_path.
  • Open the source file at source_path in binary read mode ('rb').
  • Open the destination file at dest_path in binary write mode ('wb').
  • Read the entire contents from the source file and write them to the destination file.
  • Use with statements to ensure both files are properly closed, even if an error occurs.

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 4
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt