Open file and read contents
A common task is to open files and use the contents for various reasons. Even though most of the time these days we use databases instead, it’s still good to learn these basic skills as it’s considerably faster than setting up databases and permissions for basic tasks.
We’ll create a text file called my_file.txt and put some text inside.
filename = 'my_file.txt'
text = open(filename)
print "Contents of: " + filename
As you can probably guess, filename is the variable which contains my_filename.txt, which is simply the location of the text file. text is the file handle, and text.read() tells python to bring in the contents of the file into our script. print as always will print out the text to the terminal window.