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 '
>>>