I/O in Python

Reading or Writing to an I/O device is very much easier than reading Human mind!

The first on amongst the many functions in Python which helps in I/O is raw_input()

raw_input(); the name itself suggests , the input is in the raw format , that is it's simply returns the string read from the user {ending with new line char}. An argument to it , is displayed as a prompt before the user enters the data.

Ex :

print raw_input('What is your name?')

o/p : What is your name ? { waits until user types and hits enter }

Next up is input() , it uses raw_input to read a string of data, and then attempts to evaluate the same and return the value of evaluation.


x = input('Give me 5 random numbers please')

if the user enters 1 2 3 4 5 , the input function will return me a list {1,2,3,4,5} !!

File Input

File can be handled very easily in python , the following example makes it clear.

for line in open('try.txt', 'r'):

print line[0]

Two lines to open read and print the lines in the file , on to the console!!

Line one is to open the file , it can be 'r', 'w', or 'rw', or any combination of them and the read data is stored in the line variable and is looped till EOF .

Line two as simple as it is , printing the data read in the loop.

P.S : The looping can be done in other was also

__stdin__, __stdout__, and __stderr__ are standard file objected defined in sys module .

The simple example on how to use sys module is shown below :

import sys

for line in sys.stdin:

print line

This reads line form user and prints it on the stdout , it's read from stdin.

Different functions in the sys library can be found in : sys

Similarly sys.stdout.write can be used to write

import sys

write = sys.stdout.write






the o/p will be : heman

This is just a simple post , an glimpse on the giant mountain called I/O in python.

Share this