Read the file
To open a file object in read-file mode, use the Python built-in open () function to pass in file names and identifiers:
>>> f = open ('/users/michael/test.txt ', ' R ')
The identifier ' R ' means read, so that we have successfully opened a file.
If the file does not exist, the open () function throws a IOError error and gives the error code and detailed information telling you that the file does not exist:
>>> f=open ('/users/michael/notfound.txt ', ' R ')
Traceback (most recent):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '/users/michael/notfound.txt '
If the file opens successfully, the next call to the Read () method reads the entire contents of the file at once, and Python reads the contents into memory, denoted by a str object:
>>> f.read () ' Hello, world! '
The final step is to call the close () method to shut down the file. The file must be closed after it is used because the file object consumes the resources of the operating system, and the number of files that the operating system can open at the same time is limited:
>>> F.close ()
Since the close () method is required to shut down the file after each processing of the file, many times you may forget to write it, so Python introduces the WITH statement to automatically help us call the Close () method:
With open ('/path/to/file ', ' R ') as F:
Print F.read ()
This method makes the code more concise and does not have to call the F.close () method , where Open () is the same as file (), which is the same as the alias relationship.
This article is from the DBA Sky blog, so be sure to keep this source http://9425473.blog.51cto.com/9415473/1692764
Python Read file