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