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.
Example
#!/usr/bin/python
print "Python is really a great language,", "isn't it?";
Output
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
raw_input
It reads a single line as string from the input.
Example
#!/usr/bin/python
str = raw_input("Enter your input: ");
print "Received input is : ", str
Output
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.
Example
#!/usr/bin/python
str = input("Enter your input: ");
print "Received input is : ", str
Output
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.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opened file
fo.close()
Output
Read String is : Python is
Current file position : 10
Again read String is : Python is