Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I read and write file in one line with Python?

with ruby I can

File.open('yyy.mp4', 'w') { |f| f.write(File.read('xxx.mp4')}

Can I do this using Python ?

like image 960
why Avatar asked Nov 30 '22 05:11

why


1 Answers

Sure you can:

with open('yyy.mp4', 'wb') as f:
    f.write(open('xxx.mp4', 'rb').read())

Note the binary mode flag there (b), since you are copying over mp4 contents, you don't want python to reinterpret newlines for you.

That'll take a lot of memory if xxx.mp4 is large. Take a look at the shutil.copyfile function for a more memory-efficient option:

import shutil

shutil.copyfile('xxx.mp4', 'yyy.mp4') 
like image 76
Martijn Pieters Avatar answered Dec 04 '22 23:12

Martijn Pieters