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