Friday, January 16, 2015

Hello World!

I'm starting with the basic Hello World! I don't really know much about it at this point and don't really have a guide I'm working off of.

Basic Hello World

Attempt 1:
print "Hello World!"
Seems to work just fine.

That was easy enough, but not particularly useful. It was actually an accident that I left off a semi colon, but it doesn't seem to care. I'll have to check for best practices once I get a little bit deeper. Next step, reading and writing from a file. I can't really guess the syntax on this so I'm going to Google it. I went with this site... http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python and it seems to be what I'm looking for.

Read from a file

Attempt 1:

f = open('HelloWorld1.py', 'r')
print f
This did not work and gave me this error <open file 'HelloWorld1.py', mode 'r' at 0x0000000001F120C0> 

I scrolled further down the page, and I'm not sure why that seemed to be an example, but later there is a better one leading to the next attempt.

Attempt 2:


f = open('HelloWorld1.py', 'r')
print f.read()
This worked, printing out my first example.

Scrolling further down the page you find what I was really looking for the read and write how-to snippets of code. So the first example threw me off, but this now looks a lot like Perl with only minor differences.

So now that we can read, lets also write and of course there isn't much point to writing the exact same thing you just read.

Write to a file

Attempt 1:
file_in = open('HelloWorld1.py', 'r')
file_in_content = file_in.read()
file_out = open('TestOut.txt', 'w')
file_out.write(file_in_content + '\n--- A little bit extra ---')
 This works as expected.






No comments:

Post a Comment