Blogger Themes

Search This Blog | Copyright © 2017 | All Rights Reserved | Nithin Pradeep . Theme images by Storman. Powered by Blogger.

Follow by Email

Popular KOZHI



Blogger Tricks


What is an Embedded System?

An embedded system is a combination of hardware and software that is designed to carry out a certain task or tasks, meaning it has a s...


Popular Posts


Search results

Search This Blog


More Links




Friday, 25 August 2017

Files In Python

In todays section we will see how we can create and do some operations on a file.
to see the list of supported functions type dir(file) in prompt.
see the following code below and understand.,I have created a dummy file called data (vi data) and it has following contents in it.

create a file called and type the following code:
#! /usr/bin/python
print fh.close                              #will print false because file is openprint fh.mode                               #will print mode of file that is open                   print                              #will print name of file that is open
print fh.fileno()                              #will give default file descriptor that is openfh.close()                              #will close file
The program will give output as

Reading contents of a file

fh.readlines() will give each lines in list format.

>>> print fh.readlines()
['Hello all\n', 'Good morning\n', 'welcome to\n', 'How is the weather today\n', '123456789\n', '\n']


  • Write a program to print contents of file word by word
  • Write a program to implement wc command along with file name
  • Write a program to implement head  and tail command (head command will print first 10 lines in a file by default and tail will print last 10 lines)

Writing contents to a file


 The first  code will create a file and write data inputed to the file after creating data1.
Second will write line by line to the file from list after creating data1.

Taking Arguments from command line

we need to give command line argument as:
 output will be like:
0      -first fh.tell() will give starting of file pointer
10   - after reading 10 lines pointer points to 10th place.
88 is same like fseek in c ,second argument 2 means position is at end
83  -seeking 5 position backwards from the end.

In the next section we will discuss about Regular expressions in Python...
 <<Previous                                                                                                                                     Next>>

0 on: "Files In Python"