3 ways to read Python files and path escape

Source: Internet
Author: User
Tags exception handling

This article mainly introduces Python file read 3 methods and path escape, this article gives the code to read the file example, finally explained the path to escape the relevant knowledge, tips, the need for friends can refer to the

1. Reading and displaying of files

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

Python is closed every time the file is opened, but it may cause an exception to be closed, so it is best to turn it off manually, method two through exception handling, method three through with from Invoke Close method, the easiest.

Here the open address needs to be noted that if we write open (' G:2.txt ', ' R ') the runtime will make an error: IOError: [Errno] Invalid mode (' R ') or filename: ' G:x02.txt '. This is because the path is escaped so you can use '/' instead of ': F=open (' G:/2.txt ', ' r ') or add R ' path ': F=open (R ' G:2.txt ', ' R ') is OK.

Here is a test of how to escape with the Ide-gui from Python:

The code is as follows:

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

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

>>> f= ' G:a.txt '

>>> Print F

G:.txt #这里被转义成一个特殊符号了.

>>> f1= ' G:a.txt '

>>> Print F1

G:a.txt #没被转义

>>> R ' G:a.txt '

' G:a.txt ' #没被转义

>>> ' G:a.txt '

' G:x07.txt ' #这里将a转义

>>> ' G:a.txt '

' G:a.txt '

>>>

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.