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:

print(line,end=’’)

do the same thing as mentioned in above loop

 

# Creating a new file with text from old file

def main()

infile=opemn(‘line.txt’,’r’)

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

for line in infile:

print(line,file=outfile,end=’’)

print(‘done’)

if __name__=”__main__”

                                                     

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

def main()

buffersize=50000

infile=open(‘line.txt’,’r’)

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

buffer=infile.read(buffersize)

while len(buffer):

outfile.write(buffer)

print(‘.’end=’’)

buffer=infile.read(buffersize)

print(‘done’)

if __name__=”__main__”

# Working with binary file like jpg – creating exact duplicate

def main():
    buffersize=50000
    infile = open(‘olives.jpg’,’rb’)
    outfile=open(‘new.jpg’,’wb’)
    buffer = infile.read(buffersize)
    while len(buffer):
        outfile.write(buffer)
        print(‘.’,end=”)
        buffer=infile.read(buffersize)
    print()
    print(‘Done’)   

if __name__ == “__main__”: main()

Advertisements

One response 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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: