Tutorial:Jython/IO
Input and output
Formatted output
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.
<jc lang="python"> a=8.62 print "My output=%f",a </jc> This string
%f
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:
<jc lang="python"> a=8.62526181 print "My output=%.4f",a </jc>
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:
<jc lang="python"> a=8.62526181 print "My output=%10.3f",a </jc>
File input and output
![]() | warning>
Due to some restrictions, please use a stand-alone version of the Python code editor and run these example using stand-alone application. You can get this application here |
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