File methods
In this section i would like to show you some file methods.
Whenever we use open( ) function, a file object is created.
Ex
>>> f=open(“vms.txt”,’w+’) #Created vms.txt file |
The below are some of the functions to call on this object.
1.fileno( )
The method fileno( ) returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.
Syntax
fileObject.fileno( ) |
Ex
>>> f_id=f.fileno( )
>>> f_id 3 |
2.isatty( )
The method isatty( ) returns True if the file is connected (is associated with a terminal device) to a tty(-like) device, else False.
Syntax
fileObject.isatty( ) |
Ex
>>> val=f.isatty( )
>>> val False |
3.write( )
The method write( ) writes a string str to the file.
Syntax
fileObject.write( str ) |
Ex
>>> f=open(“vms.txt”,’w’)
>>> f.write(“Some programming languages are:\nC\nC++\nJava\nPython\nPHP”) 53 |
4.read( )
The method read( ) reads at most size bytes from the file. If the read hits EOF before obtaining size bytes, then it reads only available bytes.
Syntax
fileObject.read( size ); |
Ex
>>> f=open(“vms.txt”,’r’)
>>> f.read(11) ‘Some progra’ >>> f.read(7) ‘mming l’ >>> f.read(1) ‘a’ >>> f.read( ) ‘Some programming languages are:\nC\nC++\nJava\nPython\nPHP’ |
5.flush( )
The method flush( ) flushes the internal buffer, like stdio’s fflush. This may be a no-op on some file-like objects.Python automatically flushes the files when closing them.
Syntax
fileObject.flush( ) |
Ex
>>> f.flush( ) |
It prints nothing.
6.tell( )
It returns the current position of the file read/write pointer within the file.
Syntax
fileObject.tell( ) |
Ex
>>> f=open(“vms.txt”,’r’)
>>> f.read(6) ‘Some p’ >>> f.tell( ) 6 >>> f.read(8) ‘rogrammi’ >>> f.tell( ) 14 |