Python file operations

Source: Internet
Author: User

File operations, as the name implies, is the existence of files on the disk for various operations, text files are read and write.

1. Procedures for document Operation

(1) Open the file, get the file handle and assign a value to a variable

(2) manipulating the file with a handle

(3) Close the file

Existing file

1 I smell the water in the cave, and Yueyanglou this day.  2 chu Southeast che, the Universe floats day and night.  3 friends and relatives without a word, tendencies have solitary boat.  4 rongma Guanshan North, with Xuan nasal flow.
2. Open mode of the file

To open the file's mode:

Three basic modes:

1. R, read-only mode (default)

2. W, write-only mode. (Unreadable, non-existent file created, delete content exists)

3. A, append mode. (no file is created, there is append at the end of the file)

"+" means you can read and write a file at the same time

4.r+, can read and write. (Read the file from the beginning of the file, write the file to jump to the end of the file to add)

5.w+, can write read. (the file does not exist, the file exists, the file is emptied, and then it can be written and readable)

6.a+, readable, read and write are all starting at the end of the file.

"U" means that the \r\n\r\n can be automatically converted to \ n (in conjunction with R or r+ mode) while reading

7.rU

8.r+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows needs to be labeled when processing binary files)

9. RB

10.wb

11.ab

3. File specific operation
defRead (self, size=-1):#known case of _io. Fileio.read        """Note that you may not be able to read it all back. Read at most size bytes, returned as bytes.        Only makes one system call, so less data is returned than requested.        In non-blocking mode, returns None if the data is available.        Return an empty bytes object at EOF. """        return ""defReadLine (self, *args, * *Kwargs):PassdefReadLines (self, *args, * *Kwargs):PassdefTell (self, *args, **kwargs):#Real Signature Unknown        """Current file position.        Can raise oserror for non seekable files. """        PassdefSeek (self, *args, **kwargs):#Real Signature Unknown        """Move to new file position and return the file position.  Argument offset is a byte count. Optional argument whence defaults to Seek_set or 0 (offset from start of file, offset should be >= 0); Other values is seek_cur or 1 (move relative to current position, positive or negative), and seek_end or 2        (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file).        Note that not all file objects is seekable. """        PassdefWrite (self, *args, **kwargs):#Real Signature Unknown        """Write bytes B to file, return number written.        Only makes one system call, so is not all of the data is written.  The number of bytes actually written is returned.        In non-blocking mode, returns None if the write would block. """        PassdefFlush (self, *args, * *Kwargs):PassdefTruncate (self, *args, **kwargs):#Real Signature Unknown        """Truncate the file to in most size bytes and return the truncated size.        Size defaults to the current file position, as returned by Tell ().        The current file position was changed to the value of size. """        PassdefClose (self):#real signature unknown; restored from __doc__            """Close the file.  A closed file cannot is used for further I/O operations.            Close () May is called more than once without error. """            Pass############################################################# #less Usefull    defFileno (self, *args, **kwargs):#Real Signature Unknown            """Return The underlying file descriptor (an integer)."""            Pass    defIsatty (self, *args, **kwargs):#Real Signature Unknown        """True If the file is connected to a TTY device."""        Pass    defReadable (self, *args, **kwargs):#Real Signature Unknown        """True If file is opened in a read mode."""        Pass    defReadAll (self, *args, **kwargs):#Real Signature Unknown        """Read all data from the file, returned as bytes.  In non-blocking mode, returns as much as are immediately available, or None if no data is available.        Return an empty bytes object at EOF. """        Pass    defSeekable (self, *args, **kwargs):#Real Signature Unknown        """True if file supports Random-access."""        Pass    defWritable (self, *args, **kwargs):#Real Signature Unknown        """True If file is opened in a write mode."""        PassHow to operate this method
Specific Operation

1 open () file2 Close () closes the file3 4f = open ('Noboribetsu Yueyanglou','R')5 Print(F.read ())#Read all6>>>7 I smell the water in the cave, and Yueyanglou this day. 8 chu Southeast Che, the Universe floats day and night. 9 Friends and relatives without a word, tendencies have solitary boat. Ten Rongma Guan bei, with a Xuan Si Liu One  A Print(F.read (5))#Read 5 characters ->>> - I smell the water in the cave the  - Print(F.readline ())#read a row - Print(F.readline ())#continue execution, read Next line ->>> + I smell the water in the cave, and Yueyanglou this day.  -  + chu Southeast Che, the Universe floats day and night.  A  at Print(F.readlines ())#read a file as a list ->>> -['I smell the water in the cave, and Yueyanglou this day. \ n','chu Southeast Che, the Universe floats day and night. \ n','Friends and relatives without a word, tendencies have solitary boat. \ n','Rongma Guan Shan North, with Xuan tears si flow. '] -  forIinchf.readlines (): -     Print. IO ->>> in I smell the water in the cave, and Yueyanglou this day.  -  to chu Southeast Che, the Universe floats day and night.  +  - Friends and relatives without a word, tendencies have solitary boat.  the  * Rongma Guan Shan North, with Xuan tears si flow.  $ You can also use: (recommend this method)Panax Notoginseng  forIinchF: -     Print(i) the      + Print(F.tell ())#indicates where the cursor is located r mode open file default cursor at initial position 0 A>>> the 0 +  -f = open ('Noboribetsu Yueyanglou','R', encoding='Utf-8') $ Print(F.tell ()) $F.seek (5) - Print(F.tell ()) ->>> the 0 -5Wuyi F.seek () is used to adjust the cursor position similar to a wire break when downloading the  -f = open ('Noboribetsu Yueyanglou','W', encoding='Utf-8') WuF.write ('Hello World') ->>> About Hello World $ #opening a file in W mode clears all the contents of the file and then adds the contents of the write () -  -F.flush ()#when writing a file, the content is not written directly to the file, but stored in memory, and so on when the file is close before writing to the file, the flush () method is to write the contents of the memory immediately to the file. Available for progress bars -  Af = open ('Noboribetsu Yueyanglou','W', encoding='Utf-8') +F.write ('Hello World') theF.truncate (4)#Truncate content ->>> $Hell

With statement

To prevent us from forgetting the close () file after a file operation, you can use the WITH statement to manipulate the file,

 1  with open ( "  Yueyanglou  ,    R  , Encoding="  utf-8   " ) as F:  2  print   (F.read ())  3  >>>4   and the water in the cave, this Yueyanglou.  5   Chu Southeast Che, the Universe floats day and night.  6   7  Rongma in the north, with the shed tears. 

When the WITH statement finishes executing, the file is closed by default.

Python file operations

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.