[Tutor] Hello World in Python without space

Richard D. Moores rdmoores at gmail.com
Sat Jul 16 00:58:55 CEST 2011


On Fri, Jul 15, 2011 at 14:47, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Richard D. Moores, 15.07.2011 23:21:

>> 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)

Yes, went with

with open("C:\\test\\test.txt", "a+") 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.

Oops. I'd forgotten about that.

Thanks very much, Stefan and Donald.

Dick


More information about the Tutor mailing list