Python file reading methods and path escaping,
1. File Reading and display
Method 1:
Copy codeThe Code is 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 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:
Copy codeThe 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'
>>>