Can I read and write a file on one line using Python?

with ruby ​​i can

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

Can I do this using Python?

+4
source share
2 answers

Of course you can:

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

Pay attention to the binary mode flag ( b ), since you are copying the contents of mp4 , you do not want python to re-interpret newlines for you.

It will take a lot of memory if xxx.mp4 is large. Take a look at the shutil.copyfile function for more efficient use of memory:

 import shutil shutil.copyfile('xxx.mp4', 'yyy.mp4') 
+18
source

Python is not going to write ugly single-line code.

Check the documentation for the shutil module, in particular the copyfile () method.

http://docs.python.org/library/shutil.html

+3
source

Source: https://habr.com/ru/post/1434207/


All Articles