Python file _ reading,
1. File Reading and display
Method 1:
1 f=open(r'G:\2.txt')2 print f.read()3 f.close()
Method 2:
1 try:2 t=open(r'G:\2.txt')3 print t.read()4 finally:5 if t:6 t.close()
Method 3:
1 with open(r'g:\2.txt') as g:2 for line in g:3 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:
1 Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32 2 Type "copyright", "credits" or "license () "for more information. 3 >>> f = 'G: \ a.txt '4 >>> print f 5g :. txt # It is escaped as a special symbol. 6 >>> f1 = 'G: \ a.txt '7 >>> print f1 8g: \ a.txt # not escaped 9 >>> r'g: \ a.txt '10' g: \ a.txt '# not escaped 11 >>> 'G: \ a.txt '12' g: \ x07.txt '# escape a 13 >>> 'G: \ a.txt '14' g: \ a.txt '15 >>>