Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a stream in Python

Tags:

python

io

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.

like image 512
phihag Avatar asked May 16 '11 07:05

phihag


People also ask

How do you create a stream in Python?

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.

What is file stream in Python?

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.


1 Answers

shutil.copyfile and shutil.copyfileobj for the rescue. See http://docs.python.org/library/shutil.html#module-shutil

like image 71
abbot Avatar answered Sep 29 '22 13:09

abbot