Open (Filename,mode,buffer)
The first parameter is the file name of the file you want to open, the second is open, optional, and the third is a buffer, optional. By default, the file is opened in read mode. The function returns the stream type object.
Mode has the following types:
R: Read mode (default)
W: Write mode
A: Append write mode
B: Binary mode
T: Text mode (default)
+: Update existing hard drive files (read and write mode)
U: Universal Wrapping Mode (Universal New line model)
If there are no open files or other problems, you will run out of ioerror exceptions.
Common File Object properties:
Mode: File open mode
Name: Open file names
Closed: file is closed
Common file Object methods are:
Tell (): Gets the position that is currently in the current file. The starting value is 0.
Seek (Position,mode): Moves in the current file. The first argument is the distance to move, and the second argument is mode: 0 for moving the absolute position, relative to the file header, and 1 for moving the relative position, and 2 for the current position, relative to the end of the file.
Read (max_byte_num): reads bytes from a file. Max_byte_number is an optional parameter that represents the maximum number of bytes read. If not selected, the default is read to the end of the file. When read, the current position changes, increasing the number of bytes read.
ReadLine (): One line to read a file at a time.
Write (content): writes data to a file. Content is what you want to write.
Close (): Closes file
An example of a file reading and writing:
Copy Code code as follows:
Try:
f = open (' D:/hello_python.txt ', ' W ')
f.write (' Hello my friend python! ')
except IOError:
print (' ioerror ')
Finally:
f.close (
Try:
f = open (' D:\hello_python.txt ', ' R ')
print (f.read ())
f.close ()
f.tell ()
except ValueError as IOError: Br> print (' File alread closed {0} '. Format (type (ioerror))
Finally:
print (' Operation End ')