3 ways to read Python files and path escapes

Source: Internet
Author: User
1. Read and display the file

Method 1:
Copy the Code code as follows:


F=open (R ' G:\2.txt ')
Print F.read ()
F.close ()


Method 2:
Copy CodeThe code is as follows:


Try
T=open (R ' G:\2.txt ')
Print T.read ()
Finally
If T:
T.close ()


Method 3:
Copy CodeThe code is as follows:


With open (R ' G:\2.txt ') as G:
For line in G:
Print Line


Although Python is closed every time the file is opened, it is possible that it is not closed because of an exception, so we'd better do it manually, method two is handled by exception handling, and method three is easiest to call the Close method through with.
Here Open's address needs to be noted, if we write open (' G:\2.txt ', ' r ') will 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 ').
Here's a test of how to escape with Python's own Ide-gui:
Copy CodeThe code is as follows:


Python 2.7.6 (default, Nov, 19:24:18) [MSC v.1500 + bit (Intel)] on Win32
Type "Copyright", "credits" or "license ()" For 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 '
>>>
  • 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.