Python
programming
Opening, Reading and Writing Binary
Files
Binary files refer to any file that contains non-text,
such as image or video
files. To work with binary files, we simply use the
‘rb’ or ‘wb’ mode. Copy
a jpeg file onto your desktop and rename it
myimage.jpg. Now edit the
program above by changing the first two line lines
inputFile = open (‘myfile.txt’
, 'r')
outputFile = open (‘myoutputfile.txt’
,
'w')
to
inputFile = open (‘myimage.jpg’
,
'rb')
outputFile = open (‘myoutputimage.jpg’
,
'wb')
Make sure you also change the statement
outputFile.write(msg +
'\n') back to outputFile.write(msg).
Run the new program. You should have an
additional image file named myoutputimage.jpg on your desktop. When you
open the image file, it
should look exactly like myimage.jpg.
Deleting and Renaming Files
Two other useful functions we need to learn when
working with files are
the remove() and rename() functions. These
functions are available in
the os module and have to be imported before we
can use them.
The remove() function deletes a file. The syntax is
remove(filename). For instance, to delete myfile.txt,
we write
remove(‘myfile.txt’).
The rename() function renames a file. The syntax is
rename (old
name, new name). To rename oldfile.txt to
newfile.txt, we
write rename(‘oldfile.txt’ ,
‘newfile.txt’).
Opening, Reading and Writing Binary
of 4
Report
Tell us what’s wrong with it:
Thanks, got it!
We will moderate it soon!
Free up your schedule!
Our EduBirdie Experts Are Here for You 24/7! Just fill out a form and let us know how we can assist you.
Take 5 seconds to unlock
Enter your email below and get instant access to your document