faqts : Computers : Programming : Languages : Python : Snippets : Stream Manipulation : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 5 people (60%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

File handles and streams

Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 155, Tim Peters


"""
Packages: files
"""
"""
> Is there an easy way to do this, i.e an equivalent of perls:
>     print OUTPUTFILE in1, in2, out
>
> or do I have to do a full C-like print into a string and write that to
> output.
Here's an easy-to-use alternative; stick it in a module and import as
needed:
"""
import sys
def fprint(file, *args):
    saveout = sys.stdout
    try:
        sys.stdout = file
        for thing in args:
            print thing,
        print
    finally:
        sys.stdout = saveout
"""
Use via e.g.
"""
# from fprint import fprint
f = open("a.txt", "w")
# prints "this is a test 5\n" to f
fprint(f, "this", "is", "a", "test", 5)
# prints to original stdout
print "done"
"""
Note that you can also pass "file-like objects", i.e. any instance of a
class that supports a method named "write".
nothing-you-can-do-in-perl-you-can't-do-in-ten-lines-of-python<wink>-ly
    y'rs  - tim
"""