How do I transfer the contents of a stream to another in Python?
The trivial solution would be
output.write(input.read())
but that fails if the input file is larger than the available memory (or even infinitely large); and it doesn't work well when a partial copy is useful as well. Basically I'm looking for the equivalent of org.apache.commons.IOUtils.copy
.
In Python, streams are "file-like" objects. You can read/write to them using tools defined in the io module. The module also provides interfaces which you should implement if you want to define a stream object.
The file object is a data stream that supports next() method to read file line by line. When end of file is encountered, StopIteration exception is raised. f=open("python.txt","r") while True: try: line=next(f) print (line, end="") except StopIteration: break f.close() Output: Beautiful is better than ugly.
shutil.copyfile
and shutil.copyfileobj
for the rescue. See http://docs.python.org/library/shutil.html#module-shutil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With