Introduction to Python File operation methods

Source: Internet
Author: User

File operations

1.open () function

The open () function is primarily used for file processing and is generally divided into the following 3 processes:

1. Open File

2. Operating files

3. Close the file

Examples of common formats:

f = open (' Note.txt ', ' R ') F.read () F.close ()

1. Open File

File handle = open (' File path ', ' mode ')

The common patterns are:

1. ' R ', read only

2. ' W ', write only (when a write-only operation is performed on the open, the original contents of the file will be emptied, note the backup)

3. ' A ', append

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

1. ' R+ '

2. ' w+ '

3. ' A + '

"B" means processing binary files

1. ' RB ', ' rb+ '

2. ' WB ', ' wb+ '

3. ' Ab ', ' ab+ '

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

1. ' RU '

2. ' R+u '

2. Operating Files

class file (object) def close (self): # real signature unknown;  Restored from __doc__ close file "" "Close () None or (perhaps) an integer.        Close the file.  Sets data attribute. Closed to True.  A closed file cannot is used for further I/O operations.  Close () May is called more than once without error.        Some Kinds of File objects (for example, opened by Popen ()) could return an exit status upon closing. "" "Def Fileno (self): # real signature unknown;        Restored from __doc__ file descriptor "" "Fileno (), integer" File descriptor ".        This is needed for Lower-level file interfaces, such Os.read (). "" "Return 0 def Flush (self): # real signature unknown;  Restored from __doc__ flush file internal buffer "" "Flush () None. Flush the internal I/O buffer. "" "Pass Def Isatty (self): # real signature unknown; Restored from __doc__ determine if the file is consent to the TTY device "" "Isatty () True or FalsE. True if the file is connected to a TTY device. "" "Return False def Next (self): # real signature unknown; Restored from __doc__ gets the next row of data, does not exist, the error "" "" "" "" "" "" X.next (), the next value, or raise Stopiteration "" "p The Size=none (self, the): # Real signature unknown;        Restored from __doc__ reads the specified byte data "" "Read ([size]), read at the most size bytes, returned as a string.        If the size argument is negative or omitted, read until EOF is reached.  Notice that while in non-blocking mode, less data than what is requested may be returned, even if no size parameter        was given. "" "Pass Def Readinto (self): # real signature unknown;  Restored from __doc__ read to buffer, do not use, will be abandoned "" "Readinto (), undocumented. Don ' t use this; It may go away. "" "Pass Def ReadLine (self, size=none): # Real signature unknown; Restored from __doc__ reads only one row of data "" "ReadLine ([size]), next lineFrom the file, as a string.  Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line is returned then)        .        Return an empty string at EOF. "" "Pass Def readlines (self, size=none): # Real signature unknown;  Restored from __doc__ reads all data and saves a list of values, "" "ReadLines ([size]), based on line break, and list of strings, each a lines from        The file.        Call ReadLine () repeatedly and return a list of the lines so read.        The optional size argument, if given, is a approximate bound on the all number of bytes in the lines returned. "" "return [] def seek (self, offset, whence=none): # Real signature unknown;  Restored from __doc__ specifies the position of the pointer in the file "" "Seek (offset[, whence]), None.        Move to new file position.  Argument offset is a byte count. Optional argument whence defaults to (offset from start of the file, offset should be >= 0);   Other values is 1     (move relative to current position, positive or negative), and 2 (move relative to end of file, usually Negati  ve, although many platforms allow seeking beyond the end of a file).  If the file is opened in text mode, only offsets returned by tell () is legal.        Use of other offsets causes undefined behavior.        Note that not all file objects is seekable. "" "Pass Def Tell (self): # real signature unknown; Restored from __doc__ gets the current pointer position "", "Tell ()", "present file position, an integer (could be a long integer). "" "Pass def truncate (self, size=none): # Real signature unknown;  Restored from __doc__ truncates the data, leaving only the specified previous data "" "Truncate ([size]), None.        Truncate the file to in the most size bytes.        Size defaults to the current file position, as returned by Tell (). "" "Pass Def write (self, p_str): # Real signature unknown; Restored from __doc__ write content "" "Write (StR), None.        Write string str to file.        Note that due to buffering, flush () or close () is needed before the file on disk reflects the data written. "" "Pass Def writelines (self, sequence_of_strings): # Real signature unknown;  Restored from __doc__ writes a list of strings to the file "" "Writelines (sequence_of_strings), None.        Write the strings to the file.  Note that newlines is not added. The sequence can is any iterable object producing strings.        This is equivalent to calling write () for each string. "" "Pass Def Xreadlines (self): # real signature unknown;        The restored from __doc__ can be used to read the file line by row, not all "" "Xreadlines ()-returns self. For backward compatibility.        File objects now include the performance optimizations previously implemented in the Xreadlines module. "" "Passpython 2.x

python2 action file

Class Textiowrapper (_textiobase): "" "Def Close (self, *args, **kwargs): # Real Signature Unknown close file Pass Def Fileno (self, *args, **kwargs): # Real Signature Unknown file descriptor pass def flush (self, *args, **k Wargs): # Real Signature unknown flush file internal Buffer pass Def isatty (self, *args, **kwargs): # Real Signature Unkno WN determine whether the file is consent TTY device Pass def read (self, *args, **kwargs): # Real Signature Unknown read the specified byte data p The readable (self, *args, **kwargs): # Real Signature unknown is readable pass def readline (self, *args, **kwargs): # Real Signature Unknown read only one row of data pass Def seek (self, *args, **kwargs): # Real Signature Unknow     n Specifies the position of the pointer in the file pass Def seekable (self, *args, **kwargs): # Real Signature unknown pointer can operate pass def tell (self, *args, **kwargs): # Real signature Unknown get pointer position pass DEF truncate (self, *args, **kwa RGS): # Real Signature UNknown truncates data, retains only specified previous data pass Def writable (self, *args, **kwargs): # Real Signature Unknown writable Pass Def write (self, *args, **kwargs): # Real Signature Unknown write content Passpython 3.x

Python3 Operating files

But in fact the common operation is that several:

F.read (3)   # Python2 indicates that the specified reads 3 bytes, and Python3 indicates that 3 characters are read! F.readline ()    # reads a row in the contents of the file F.readlines ()   # automatically resolves the contents of the file to a list of < rows, which can be used for line in F.readlines (): Handles F.write (' Hellopython ') F.seek (9)   # Executes in bytes to specify the current file pointer position, seek (0) indicates that the file pointer moves to the file header, Seek (0,2) points to the end of the file, and facilitates the addition of content F.tell ()    # is executed in bytes to view the current pointer position

There is also a truncate () function that truncates the contents of the file and preserves only the contents of the file before it is truncated, and it is not easy to understand the example:

f = open (' Test.log ', ' r+ ', encoding= ' Utf-8 ') #  encoding= ' Utf-8 ', there is a time to handle Chinese characters with F.seek (9) # The   original file content is ' After the little Apple Hellopython ' F.truncate () #执行truncate (), keep only the contents of the original file before truncation, here is the ' Little Apple ' f.close ()

2.with statements

When using the open () function for file processing, it is very troublesome to execute f.close () to close the file after the file is opened for operation. Using the WITH () statement avoids this tedious operation and automatically closes the file after the file operation. Also, the purpose of introducing the WITH statement in Python is to remove the try,except and finally keywords and the code associated with resource allocation releases in exception handling, thus reducing the amount of code written and making the code more concise!

Such as:

With open (' Name.txt ', ' W ') as F:    f.write (' Somebody^fancy1 ')

Equivalent to:

try:f = open (' Name.txt ', ' W ') f.write (' Somebody^fancy1 ') finally:if f:f.close () 
Related Article

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.