BeginnersTutorial:Tutorial/Lesson 9

From jWork.ORG
Jump to: navigation, search

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.

print "My output=%f",a

This string


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:

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:

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

Note that we have added "w" argument when oppenned the file. This means the file is open for "writing".

To open and read this file, you

a = open("output.txt")
line = a.readline()
print line
while line:
    print line

and you can skip the argument "w".

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.