Python file reading methods and path escaping

Source: Internet
Author: User

Python file reading methods and path escaping

This article mainly introduces three methods for reading Python files and path escaping. This article provides code examples for reading files, and finally explains the knowledge and tips of path escaping, for more information, see

1. File Reading and display

Method 1:

The Code is as follows:

F = open (r 'G: \ 2.txt ')

Print f. read ()

F. close ()

Method 2:

The Code is as follows:

Try:

T = open (r 'G: \ 2.txt ')

Print t. read ()

Finally:

If t:

T. close ()

Method 3:

The Code is as follows:

With open (r 'G: \ 2.txt ') as g:

For line in g:

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:

The Code is as follows:

Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32

Type "copyright", "credits" or "license ()" for more information.

>>> F = 'G: \ a.txt'

>>> Print f

G:. txt # It is escaped as a special symbol.

>>> F1 = 'G: \ a.txt'

>>> Print f1

G: \ a.txt # not escaped

>>> R 'G: \ a.txt'

'G: \ a.txt '# not escaped

>>> 'G: \ a.txt'

'G: \ x07.txt '# escape a here

>>> 'G: \ a.txt'

'G: \ a.txt'

>>>

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.