Python Read file

Source: Internet
Author: User

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

Related Article

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.