Beginning Python From Novice to Professional (8)-file Method

Source: Internet
Author: User

Beginning Python From Novice to Professional (8)-file Method

File Method

Read/write:

#!/usr/bin/env pythonf = open('somefile.txt','w')f.write('Hello,')f.write('World!')f.close()f = open('somefile.txt','r')print f.read(5)
Hello
Basic file method:

#!/usr/bin/env pythonf = open(r'somefile.txt')print f.read()f.close()f = open(r'somefile.txt')for i in range(3):print str(i) + ':' + f.readline()f.close()import pprintpprint.pprint(open(r'somefile.txt').readlines())f = open('somefile.txt','w')f.write('we\nchange\nthis file!')f.close()f = open(r'somefile.txt')print f.read()f.close()f = open(r'somefile.txt')lines = f.readlines()f.close()lines[1] = "changed\n"f = open(r'somefile.txt','w')f.writelines(lines)f.close()f = open(r'somefile.txt')print f.read()f.close()
Thisis aTest!0:This1:is a2:Test!['This\n', 'is a\n', 'Test!\n']wechangethis file!wechangedthis file!
File unpacking:

#!/usr/bin/env pythonf = open(r'somefile.txt','w')f.write('First line\n')f.write('Second line\n')f.write('Third line\n')f.close()lines = list(open('somefile.txt'))print linesfirst,second,third = open('somefile.txt')print firstprint secondprint third
['First line\n', 'Second line\n', 'Third line\n']First lineSecond lineThird line

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.