[Tutor] Hello World in Python without space

Stefan Behnel stefan_ml at behnel.de
Fri Jul 15 23:47:23 CEST 2011


Richard D. Moores, 15.07.2011 23:21:
> On Sun, Jul 10, 2011 at 05:05, Peter Otten wrote:
>
>> >>> help(print)
>>
>> shows
>>
>> print(...)
>>     print(value, ..., sep=' ', end='\n', file=sys.stdout)
>>
>>     Prints the values to a stream, or to sys.stdout by default.
>>     Optional keyword arguments:
>>     file: a file-like object (stream); defaults to the current sys.stdout.
>>     sep:  string inserted between values, default a space.
>>     end:  string appended after the last value, default a newline.
>
> I didn't know that printing to a file with print() was possible, so I tried
>
> >>> print("Hello, world!", file="C:\test\test.txt")
> Traceback (most recent call last):
>    File "<string>", line 1, in<fragment>
> builtins.AttributeError: 'str' object has no attribute 'write'
> >>>
>
> And the docs at
> <http://docs.python.org/py3k/library/functions.html#print>  tell me
> "The file argument must be an object with a write(string) method; if
> it is not present or None, sys.stdout will be used."
>
> What do I do to test.txt to make it "an object with a write(string) method"?

Oh, there are countless ways to do that, e.g.

   class Writable(object):
       def __init__(self, something):
           print("Found a %s" % something))
       def write(self, s):
           print(s)

   print("Hello, world!", file=Writable("C:\\test\\test.txt"))

However, I'm fairly sure what you want is this:

     with open("C:\\test\\test.txt", "w") as file_object:
         print("Hello, world!", file=file_object)

Look up "open()" (open a file) and the "with statement" (used here 
basically as a safe way to make sure the file is closed after writing).

Also note that "\t" refers to a TAB character in Python, you used this 
twice in your file path string.

Stefan



More information about the Tutor mailing list