Python Files I/O - PYTHON PROGRAMMING (2010)


Python Files I/O

One of the basic methods to produce output is by using print statement where one can pass zero and more expressions.



print "Python is really a great language,", "isn't it?";


Python is really a great language, isn't it?

Reading keyboard input

It is a built in function with a line of text to perform various functions. These functions are as follows.

· raw_input

· input


It reads a single line as string from the input.



str = raw_input("Enter your input: ");

print "Received input is : ", str


Enter your input: Hello Python

Received input is: Hello Python

Input function

Its functionality is similar to the raw_input function but it has an exception that is it considers it as a python operation in whole.



str = input("Enter your input: ");

print "Received input is : ", str


Enter your input: [x*5 for x in range(2,10,2)]

Recieved input is: [10, 20, 30, 40

File position

· The tell() tells you the present position within the file.

· The seek() changes the present file position. The from argument specifies the position to be referred from where the bytes are to be transferred.

· If it is set to 0, that means use of the beginning of the file as the particular reference position and 1 means to use the current position as the referenced position and if set to 2 then its end of the file which would be taken to be the reference position.



# Open a file

fo = open("foo.txt", "r+")

str =;

print "Read String is : ", str

# Check current position

position = fo.tell();

print "Current file position : ", position

# Reposition pointer at the beginning once again

position =, 0);

str =;

print "Again read String is : ", str

# Close opened file



Read String is : Python is

Current file position : 10

Again read String is : Python is