Python file operation instance code

Source: Internet
Author: User

#! /Usr/bin/env python

01 #! /Usr/bin/env python

02 # coding: UTF-8

03 # Author: Cool

04 # Purpose: file operation class

05 # Created: 2011/1/1

06

07 # declare a string text

08 poem = '''\

09 Programming is fun Test

10 When the work is done

11 if you wanna make your work also fun:

12 use Python!

13 '''

14 # create a file instance in the read-only mode ('R'), write mode ('W'), and append mode ('A ')

15 f=file('poem.txt ', 'A') # open for 'W' riting

16 f. write (poem) # write text to the file write text to file

17 f. close () # close the file

18

19 # the default mode is read-only.

20 f=file('poem.txt ')

21 # if no mode is specified, 'R' ead mode is assumed by default

22 while True:

23 line = f. readline () # Read every row of the file

24 if len (line) = 0: # Zero length indicates EOF

25 break

26 print line, # output this line

27 # Note: because the content read from the file has ended with a line break, we use a comma in the output statement to eliminate line breaks.

28

29 # Notice comma to avoid automatic newline added by Python

30 f. close () # close the file

31

32 # Help

33 help (file)

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.