# JythonTutorial:IO

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Contents

# 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.

a=8.62
print "My output=%f",a

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:

a=8.62526181
print "My output=%.4f",a

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:

a=8.62526181
print "My output=%10.3f",a

## File input and output

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")