File Handling in Python PDF
File Handling in Python PDF
Tushar B. Kute,
http://tusharkute.com
What is a file ?
• f = open("test.txt")
# equivalent to 'r' or 'rt'
• f = open("test.txt",'w')
# write in text mode
• f = open("img.bmp",'r+b')
# read and write in binary mode
• f = open("test.txt",mode =
'r',encoding = 'utf-8')
# Specfied with encoding
Reading functions
• read(n)
– Read atmost n characters form the file. Reads till end
of file if it is negative or None.
• readable()
– Returns True if the file stream can be read from.
• readline(n=-1)
– Read and return one line from the file. Reads in at
most n bytes if specified.
• readlines(n=-1)
– Read and return a list of lines from the file. Reads in at
most n bytes/characters if specified.
read( )
readline( )
readlines( )
Example:
with open("test.txt",'w') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
File writing methods
• writable()
– Returns True if the file stream can be written
to.
• write(s)
– Write string s to the file and return the
number of characters written.
• writelines(lines)
– Write a list of lines to the file.
Sample File copy operation
Example:
• We can change our current file cursor (position) using the seek()
method.
• Similarly, the tell() method returns our current position (in number of
bytes).
>>> f = open('test.txt')
>>> f.readline()
'Hello All,\n'
>>> print f.tell()
11
>>> f.readline()
'This is Tushar Kute,\n'
>>> print f.tell()
32
Seeking
>>> f = open('test.txt')
>>> f.readline()
'Hello All,\n'
>>> f.readline()
'This is Tushar Kute,\n'
>>> f.seek(0)
>>> f.readline()
'Hello All,\n'
>>> f.seek(11)
>>> f.readline()
'This is Tushar Kute,\n'
Problem Statements:
Web Resources
http://mitu.co.in
http://tusharkute.com
contact@mitu.co.in
tushar@tusharkute.com