Python File Reading

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.