As with everything in Python, files are objects. To open a file object, you must assign it to a variable as follows:
a = open("sample.txt")
By default, the open command takes a minimum of one and possibly two arguments: the name of the file to open and the control, or permission, you would like the program to exercise over that file. The two basic ways to open a file are for reading ('r') and writing ('w'). If the file is a binary file, instead of text, you can follow the 'r' or the 'w' with a 'b' to tell Python to deal with the file accordingly.
The following example opens a file for reading. It then reads every line of the file, printing it to the screen, and closes the file at the end.
a = open("sample.txt", "r") line = a.readline() while line: print line line = a.readline() # Note that the content of line changes # here, resetting the loop a.close()
Writing to a file is even easier. The following code opens a file, 'output.txt', for writing and writes a sample line to it, complete with a newline at the end.
a = open("output.txt", "w") a.write("This is a sample line.\n")