Python file operation implementation code

  • 2020-04-02 09:31:29
  • OfStack

Open (filename, mode, buffer)
The first parameter is the filename of the file to be opened. The second is the open mode, which is optional; The third buffer is optional. By default, the file is opened in read mode. This function returns a 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 disk files (read and write mode)
U: Universal new line mode
If the open file does not exist or other problems, an IOError exception will run.
Common file object properties:
Mode: file open mode
Name: the name of the open file
Closed: whether the file is closed
Common file object methods are:
Tell () : gets the current location in the current file. The starting value is 0.
Seek (position,mode) : move in the current file. Where the first parameter is the distance to move, the second parameter is the mode: 0 means the absolute position to move, relative to the file header; 1 represents moving relative position, in terms of the current position; 2 represents the 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, the default is to read to the end of the file. After a read, the current position changes, increasing the number of bytes read.
Readline () : reads one line of a file at a time.
Write (content) : writes data to a file. Content is the content to be written.
Close () : closes the file
An example of a file read and write:
 
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') 

Related articles: