Roshan Book

My Tech Notebook

Python tutorial 14.2–input and output


Opening a file – read mode

def main():
    f = open(‘lines.txt’)
    for line in f:
        print(line, end = ”)

if __name__ == “__main__”: main()

f = open(‘lines.txt’,’r’) – open just to read a file. Default

f = open(‘lines.txt’,’w’) – write mode

f = open(‘lines.txt’,’a’) – append, what you write gets appended
f = open(‘lines.txt’,’r+’) – read and write
f = open(‘lines.txt’,’rt’) – text file mode

f = open(‘lines.txt’,’rb’) – binary mode

for line in f.readlines:


do the same thing as mentioned in above loop


# Creating a new file with text from old file

def main()


outfile=open(‘new.txt ’,w)  # new file which we want to create

for line in infile:



if __name__=”__main__”


This will create a new file new.txt with content from line.txt

def main()



outfile=open(‘new.txt ’,w)  # new file which we want to create

while len(buffer):




if __name__=”__main__”

# Working with binary file like jpg – creating exact duplicate

def main():
    infile = open(‘olives.jpg’,’rb’)
    buffer =
    while len(buffer):

if __name__ == “__main__”: main()


4 responses to “Python tutorial 14.2–input and output

  1. Emery Ohlsson October 22, 2011 at 12:32 pm

    Good page… Just killing some time browsing searches and found your site. Great looking website. I’ll have to save the blog to come back and see what’s new. Cheers! My Blog: Lethalia Blogs

  2. UGG Classic Short Paisley 5831 November 17, 2011 at 10:30 pm

    Just want to say your article is as amazing. The clarity in your post is just excellent and that i could suppose you are an expert on this subject. Well with your permission let me to take hold of your RSS feed to keep up to date with forthcoming post. Thanks a million and please carry on the enjoyable work.

  3. Fake Louis Vuitton Belt December 5, 2011 at 7:17 am

    This is my first time i visit here. I discovered so a lot of entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I’m not the only 1 having all the enjoyment here! Maintain up the very good work.

  4. Cheap Designer Handbags December 6, 2011 at 7:47 am

    Surprisingly useful thank you, It looks like your trusty followers would possibly want a lot more details similar to this preserve the fantastic effort.

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

%d bloggers like this: