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 p1.py and type the following code:
False
r
data
3
fh.readlines() will give each lines in list format.
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 p1.py and type the following code:
#! /usr/bin/python fh=open('data','r') print fh.close #will print false because file is openprint fh.mode #will print mode of file that is open print fh.name #will print name of file that is open print fh.fileno() #will give default file descriptor that is openfh.close() #will close fileThe program will give output as
False
r
data
3
Reading contents of a file
fh.read()
>>> print fh.readlines()
['Hello all\n', 'Good morning\n', 'welcome to embeddedstudy.com\n', 'How is the weather today\n', '123456789\n', '\n']
ASSIGNMENTS
- 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
fh.write()
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 -fh.seek() 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"