Python file _ reading,

Source: Internet
Author: User

Python file _ reading,

1. File Reading and display

Method 1:

1 f=open(r'G:\2.txt')2 print f.read()3 f.close()

Method 2:

 

1 try:2     t=open(r'G:\2.txt')3     print t.read()4 finally:5     if t:6        t.close()

 

Method 3:

1 with open(r'g:\2.txt') as g:2     for line in g:3         print line

Although python needs to be closed every time it opens a file, it may not be closed due to exceptions. Therefore, we 'd better disable it manually. Method 2: handle exceptions, you can use the with method to automatically call the close method.

Note that if we write open ('G: \ 2.txt ', 'R'), the following error occurs: IOError: [Errno 22] invalid mode ('R') or filename: 'G: \ x02.txt '. Because the path is escaped, '/' can be used instead of '\': f = open ('G:/2.txt ', 'R ') or add 'path': f = open (r 'G: \ 2.txt ', 'R.

Here, we use the ide-GUI provided by python to test how to escape it:

1 Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32 2 Type "copyright", "credits" or "license () "for more information. 3 >>> f = 'G: \ a.txt '4 >>> print f 5g :. txt # It is escaped as a special symbol. 6 >>> f1 = 'G: \ a.txt '7 >>> print f1 8g: \ a.txt # not escaped 9 >>> r'g: \ a.txt '10' g: \ a.txt '# not escaped 11 >>> 'G: \ a.txt '12' g: \ x07.txt '# escape a 13 >>> 'G: \ a.txt '14' g: \ a.txt '15 >>>

 

 

 

 

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.