Python file operations

Source: Internet
Author: User
This article describes how to operate python files. file operations 1. open () functions

Open () functions are mainly used for file processing. they are generally divided into the following three processes:

1. open the file

2. operation file

3. close the file

Common format examples:

f = open('note.txt','r')f.read()f.close()
1. open the file
File Handle = open ('file path', 'mode ')

Common modes include:

1. 'R', read-only

2. 'W', write-only (the original content of the file will be cleared after the write-only operation is performed on the Open Object. pay attention to backup)

3. 'a', append

"+" Indicates that a file can be read and written simultaneously.

1. 'R +'

2. 'W +'

3. 'A +'

"B" indicates processing binary files

1. 'RB', 'RB +'

2. 'WB ', 'WB +'

3. 'AB', 'AB +'

"U" indicates that \ r \ n can be automatically converted to \ n (used in the same mode as r or r +) during read)

1. 'Ru'

2. 'R + u'

2. operation file
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 be used for further I/O operations. close () may be called more than once without error. some kinds of file objects (for example, opened by popen () may 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 _ refresh file buffer "flush ()-> None. flush the internal I/O buffer. "pass def isatty (self): # real signature unknown; restored from _ doc _ determine whether the file agrees 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 _ get the next row of data. if the row does not exist, an error is returned. "" x. next ()-> the next value, or raise StopIteration "" pass def read (self, size = None): # real signature unknown; restored from _ doc _ read specified byte data "read ([size])-> read at most size bytes, returned as a string. if the size argument is negative or omitted, read until EOF is reached. notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. "pass def readinto (self): # real signature unknown; restored from _ doc _ read to the buffer zone. do not use it. it will be abandoned" readinto () -> uninitialized ented. don't use this; it may go away. "" pass def readline (self, size = None): # real signature unknown; restored from _ doc _ read only one row of data "readline ([size]) -> next line from the file, as a string. retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then ). return an empty string at EOF. "" pass def readlines (self, size = None): # real signature unknown; restored from _ doc _ read all data, and save the Value list "readlines ([size])-> list of strings, each a line from the file. call readline () repeatedly and return a list of the lines so read. the optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. "" return [] def seek (self, offset, whence = None): # real signature unknown; restored from _ doc _ specifies the pointer position in the file "seek (offset [, whence])-> None. move to new file position. argument offset is a byte count. optional argument whence ULTS to (offset from start of file, offset shocould be> = 0); other values are 1 (move relative to current position, positive or negative ), and 2 (move relative to end of file, usually negative, although implements platforms allow seeking beyond the end of a file ). if the file is opened in text mode, only offsets returned by tell () are legal. use of other offsets causes undefined behavior. note that not all file objects are seekable. "pass def tell (self): # real signature unknown; restored from _ doc _ get the current pointer position" tell ()-> current file position, an integer (may be a long integer ). "" pass def truncate (self, size = None): # real signature unknown; restored from _ doc _ truncate data, only retain the specified previous data "truncate ([size])-> None. truncate the file to at 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 () may be needed before the file on disk reflects the data written. "pass def writelines (self, sequence_of_strings): # real signature unknown; restored from _ doc _ write a string list to a file" writelines (sequence_of_strings) -> None. write the strings to the file. note that newlines are not added. the sequence can be any iterable object producing strings. this is equivalent to calling write () for each string. "pass def xreadlines (self): # real signature unknown; restored from _ doc _ can be used to read files row by row, not all" xreadlines () -> returns self. for backward compatibility. file objects now include the performance optimizations previusly implemented in the xreadlines module. "passPython 2.x

Python2 operation 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, ** kwargs): # real signature unknown refresh file internal buffer pass def isatty (self, * args, ** kwargs): # real signature unknown checks whether the file agrees to the tty device pass def read (self, * args, ** kwargs ): # real signature unknown pass def readable (self, * args, ** kwargs): # whether real signature unknown is readable pass def readline (self, * args, ** kwargs): # real signature unknown reads only one row of data pass def seek (self, * args, ** kwargs ): # real signature unknown specify the pointer position in the file pass def seekable (self, * args, ** kwargs): # whether the real signature unknown pointer can operate pass def tell (self, * args, ** kwargs): # real signature unknown get pointer position pass def truncate (self, * args, ** kwargs): # real signature unknown truncation data, retain only the specified data pass def writable (self, * args, ** kwargs): # whether real signature unknown can write pass def write (self, * args, ** kwargs ): # real signature unknown write content passPython 3.x

Python3 operation file

But the common operations are as follows:

F. read (3) # In python2, 3 bytes are read, and in python3, 3 characters are read! F. readline () # read a row of f. readlines () # automatically parses the file content into a <row list>. you can use for line in f. readlines (): process f. write ('hellopython') f. seek (9) # It is executed in bytes to specify the pointer position of the current file. seek (0) indicates that the file pointer is moved to the file header, and seek () points to the end of the file to facilitate content appending. tell () # is executed in bytes to view the current pointer position

There is also a truncate () function used to truncate the file contentOnly the content before the file content truncation is retained,For more information, see the following example:

F = open ('test. log', 'R + ', encoding = 'utf-8') # encoding = 'utf-8'. f is used to process Chinese characters. seek (9) # The original file content is 'Apple hellopython' f. truncate () # After truncate () is executed, only the content before the original file is truncated is retained. here it is 'Apple 'f. close ()
2. with statement

When using the open () function for file processing, you must execute f. close () to close the file after opening the file, which is very troublesome. Using the with () statement can avoid the tedious operations and automatically close the file after the file operation. In addition, the with statement is introduced in python to remove the try, exist T, and finally keywords and code related to resource allocation and release in exception handling, this reduces the amount of code writing and simplifies the code!

For example:

with open('name.txt', 'w') as f:    f.write('Somebody^Fancy1')

It is equivalent:

try:    f = open('name.txt','w')    f.write('Somebody^Fancy1')finally:    if f:        f.close()

The above is a detailed description of python file operations. For more information, see other related articles in the first PHP community!

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.