Python File Reading
To read a file, open a file object in Read mode. Use the Python built-in open () function to input the file name and identifier: >>> f = open ('/Users/michael/test.txt', 'R') 'indicates reading. In this way, a file is successfully opened. If the file does not exist, the open () function will throw an IOError and provide the error code and detailed information to tell you that the file does not exist: >>> f = open ('/Users/michael/notfound.txt', 'R') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: '/Users/michael/notfound.txt' If the file is successfully opened, call read () the method can read all the content of the file at a time. Python reads the content to the memory, which is represented by a str object: >>> f. read () 'Hello, world! 'The last step is to call the close () method to close the file. After the file is used, it must be closed because the file object occupies the resources of the operating system and the number of files that can be opened at the same time in the operating system is limited: >>> f. close () because you need to call the close () method to close the file after processing the file every time, but you may forget to write this sentence, python introduces the with statement to automatically call the close () method: with open ('/path/to/file', 'R') as f: print f. read () can simplify the code without calling f. the close () method, where open () and file () are the same and belong to the alias relationship, and can be used either.