Python file io for beginners

#File I/O in python

def main():
#Options for files
#open opens the file in read mode by default
# r = read
# r+ = read write mode
# w write
# a will append
# rt is for a text file mode
#rb for binary mode
f = open(‘1.txt’,’r’)
#Readlines is a function as open function is an iterator
for line in f.readlines():


def writetofile():
fh = open(‘ishaan.txt’,’w’)
#wrting to a file
print(“i am the best”,file = fh)

#This is used for very large files. And when you need to use the Buffer i/o modde
def useBuffer():
buffersize = 5000
infile = open(‘1.txt’)
outfile = open(‘new.txt’,’w’)
#Read from the buffer only for the first 5000 Bytes
buffer =
#Since read function is not iterable we cannot use for loop we need to use while loop
while len(buffer):
#Now once we have written from the buffer we need to read the next chunk of the file
buffer =

def readBinaryfile():
#reading an image file so we need to specify it is a binary file
infile = open(‘arrow.png’,’rb’)
# we need to mention buffer size as it is a big file

buffersize = 5000
outfile = open(‘newarrow.png’,’wb’)
buffer =
while len(buffer):
buffer =

if __name__== ‘__main__’: main()


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s