Python opens an indeterminate file directly using open

Source: Internet
Author: User

Python can use the Open command to turn on the file

File = Open ("Test.txt") # opening Files temp = File.read () # Read all contents of file Print (temp)

The other 2 parameters of open are omitted, and are opened using the default read-only method. However, if the file does not exist, the program will error.

If you want to prevent this, you need to verify that the file exists before you open it. This requires an OS module to be imported. But one has not learned, and the other open itself can be solved.

Use ' W ' write mode, or ' w+ ' read/write mode, No. Although the file does not exist, it creates the file, but overwrites it if the file exists.

This means that regardless of whether the file exists, a new file is reopened and processed.

There is also ' a ' append write mode, and ' A + ' append read and write mode. That's what I need. File exists, open the file, and the file does not exist, create a new blank file.

Note, however, that the pointer is at the end of the file after the file is opened. If you want to read the contents of a file, you need to move the pointer to the beginning and only use ' A + '. Write mode is write-only and cannot be read.

File = Open ("Test.txt", ' A + ') # Opens File.seek (0) # Moves the pointer to the beginning of temp = File.read () # reads all the contents of the file Print (temp)

This way, even if the file does not exist, it will not error, but create a new empty file open. Then we can add a judgment statement, if the read content of the file is empty, then do some initialization processing.


Python opens an indeterminate file directly using open

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.