Mar 28, 2015

Python Input and Output

In order to accept user input via console and display result, python has in built methods like raw_input() and print(). We have seen uses of print() in earlier post, reading input via console will be focus of this post. Along with console reading, Python’s support for reading and writing text files too.In this post we will see both of these in detail.

Console Input and Output:-

For acquiring information from the user console python has raw_input() (input() in python 3.0 or later) in built method. Lets write a sample program, calculate mean of numbers between range provided as user input.  i.e  user provides range (start and end) and output is displayed via print().
Open Python IDLE and Copy the following code in a file. Once we execute the following code lines, prompt will appear and will ask for user input. calculateMean(start, end) is called and mean is calculated.Using print() method mean is displayed. 
# Definition of calculateMean function 
def calculateMean(start,end):
      sum = 0
      n = (end - start)+1;
      while start <= end:
        sum = sum+start
        start = start+1
      return (float(sum) / n)

# Read user input via console 
start = int(raw_input("Enter start of range: "))
end = int(raw_input("Enter end of range: "))

# call calculateMean function
mean = calculateMean(start,end)
print "mean of numbers between %d and %d is %f" % (start, end, mean )
Sample outputs are:
>>>
Enter start of range: 8
Enter end of range: 10
mean of numbers between 8 and 10 is 9.000000
>>>
Enter start of range: 1
Enter end of range: 10
mean of numbers between 1 and 10 is 5.500000

Files input and output:-

Like others programming languages, python has built in methods to perform read and write operation in files.The very first step is to open the specified file in read or write mode. It returns a proxy for interactions with the underlying file. Once we get handle(proxy) corresponding to the file, using read() , readline() or write() we can perform required operation.Finally, once we are done we close the file using close() method. It can be summarized as following : 
# Open for writing 
f = open('input.txt', 'w')
# Write text to file
f.write("input string")
# Close the file
f.close()
Let's write a sample code for demonstrating file operation.Open a file in write mode , read the content from input file (display on console) and append block of lines in the existing file.
Open Python IDLE and create a file and copy following code lines in it. Lets walk through code lines and divide our program in thee section:
Read operation : input_block - block of lines is created for writing in file. File input.txt is opened in read mode(Default mode is read mode, if do not specify) and using readline() method file is read line by line and displayed on console. Loop is terminated once length of line is zero.And file is closed using close().
Append operation: After that file is opened in append mode(write at end of file without disturbing previous content). Using f.write(input_block) block of statements is written in file and file is closed.
Read operation after append : Once again file is opened in read mode and file content is read and displayed on console. We can spot the difference in output of section 1 and section 2, highlighted in blue colour.
input_block = """
1.hello writing!!
111.hello writing!!
11111.hello writing!!
"""

# Section 1: read operation
# Read the file content and display on console
print 'Read the file content and display on console before append'
# open file and get proxy(handle)
f = open('input.txt')
while True:
    line = f.readline()
    # Zero length indicates EOF
    if len(line) == 0:
        break
    print line,
#Close the file
f.close()

# Section 2: append operation
# Open for appending
f = open('input.txt', 'a')
# Write text to file
f.write(input_block)
# Close the file
f.close()

# Section 3: read operation after append
# Read the file content and display on console
print 'Read the file content and display on console after append'
# open file and get proxy(handle)
f = open('input.txt')
while True:
    line = f.readline()
    # Zero length indicates EOF
    if len(line) == 0:
        break
    print line,
#Close the file
f.close()
Sample output:
>>>
Read the file content and display on console before append
Hello!!
Read first line.
Append your test below
----Do not delete me------

Read the file content and display on console after append
Hello!!
Read first line.
Append your test below
----Do not delete me------

1.hello writing!!
111.hello writing!!
11111.hello writing!!
---End of sample output---


Previous: Python Functions  Next:Exception handling in python
Location: Hyderabad, Telangana, India