You are a guest. Restricted access. Read more

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

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

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.

python/io.txt · Last modified: 2013/04/14 16:52 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0