Open (Filename,mode,buffer)
The first parameter is the file name of the file to open, required, the second one is open, optional, and the third is the buffer, optional. By default, the file is opened in read mode. The function returns a stream type object.
Mode has the following types:
R: Read mode (default value)
W: Write mode
A: Append write mode
B: Binary mode
T: Text mode (default value)
+: Update existing hard drive files (read and write mode)
U: Universal newline Mode (Universal New line mode)
If there are no open files or other problems, it will run out of the ioerror exception.
Common File Object properties:
Mode: File open mode
Name: Open file names
Closed: Whether the file is closed
Common file Object methods are:
Tell (): Gets the location in the current file that is currently in place. The starting value is 0.
Seek (Position,mode): Moves in the current file. Where the first parameter is the distance to move, the second parameter is the pattern: 0 for moving the absolute position, relative to the file header, 1 for moving relative position, and 2 for the position relative to the end of the file.
Read (max_byte_num): reads bytes from the file. Max_byte_number is an optional parameter that represents the maximum number of bytes read. If not selected, the default is to read to the end of the file. After reading, the current position changes, which increases the number of bytes read.
ReadLine (): reads a single line of the file at a time.
Write (content): writes data to a file. Content is what you want to write.
Close (): Close file
An example of a file read and write:
Copy CodeThe code is 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:
Print (' File alread closed {0} '. Format (type (IOERROR)))
Finally
Print (' Operation End ')