So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file?
val = print(arg)
gets a SyntaxError.
Is there a way to access stdinput?
And why does print take forever with massive strings? Bad programming on my side for outputting massive strings, but quick debugging--and isn't that leveraging the strength of an interactive prompt?
There's probably also an easier 开发者_StackOverflowway than my gripe. Has the hive-mind an answer?
You could look into the logging module of Python. Perhaps that's the perfect match in this case.
You don't typically use print
for writing to a file (though you technically can). You would use a file object for this.
with open(filename, 'w') as f:
f.write(repr(your_thingy))
If print
is taking forever to display a massive string, it is likely that it's not exactly print
's fault, but the result of having to display all that to screen.
Seeing how you're using print
as function, docs say that you can redirect to file like this:
print(arg, file=open('fname', 'w'))
In Python 3.*
, to redirect one print
call to an open file object destination
,
print(arg, file=destination)
In Python 2.*
, where print
is a statement, the syntax is
print>>destination, arg
I imagine you're using 2.*
because in 3.*
assigning print
's result is not a syntax error (it's just useless, since that result is None
, but allowed). In 2.*
print
is a statement, not a function, so the code snippet you give is indeed a syntax error.
I'm not sure what the assignment is supposed to mean. If you want to redirect one or more print
statements (or calls) to get the formatted result as an in-memory string, you can set sys.stdout
to a StringIO
(or cStringIO
) instance; but you specifically mention "to a file" so I'm really perplexed as to the intended meaning of that assignment. Clarify pls?
I tried both examples with no success using python 2.7
To begin I created a file in C:\goat.text using notepad
Next I tried the following
import sys
print>>"C:\goat.txt", "test" error AttributeError: 'str' object has no attribute 'write'
print("test", file=open('C:\goat.txt', 'w'))
SyntaxError: ("no viable alternative at input '='", ('C:\Users\mike\AppData\Local\Temp\sikuli-tmp5165417708161227735.py', 3, 18, 'print("test", file=open(\'C:\\goat.txt\', \'w\')) \n'))
I've tried multiple variants annd can't solve this.
精彩评论