Python file operation Implementation code _python

Source: Internet
Author: User
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 ')

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.