print function used before did not format the values and we had no control over the way in which variable is printed. But one can use the operator
to produce formatted output.
indicates that Python should replace this statement with the variable.
One can control the number of decimal places the number printed to. Let us print the value to four decimal places:
Now, 10.3 forces the number to be printed to three decimal places and spaces to be inserted if necessary so that number takes up ten characters:
Writing a string into a file is very easy in Python. 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") a.close()
To open and read this file, you
a = open("output.txt") line = a.readline() print line while line: print line
As you can see, 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.