Python: file/file-like object Method

Source: Internet
Author: User

IO Read and Write File Operation Method summary! ---- The_Third_Wave study notes!

 

This article by @ The_Third_Wave (Blog address: http://blog.csdn.net/zhanh1218) original. Update from time to time. If any error occurs, please correct it.

Sina Weibo follow :@The_Third_Wave

If this blog post is helpful to you, you are not recommended to repost it for a good network environment. We recommend that you add it to your favorites! If you must reprint the content, please include the suffix and the address of this article.

Class file (object) | file (name [, mode [, buffering])-> file object
|
| Open a file. the mode can be 'R', 'w' or 'A' for reading (default), writing or appending. the file will be created if it doesn' t exist when opened for writing or appending; it will be truncated when opened for writing. add a 'B' to the mode for binary files. add a' + 'to the mode to allow simultaneous reading and writing. if the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. the preferred way to open a file is with the builtin open () function. add a 'u' to mode to open the file for input with universal newline support. any line ending in the input file will be seen as a' \ n' in Python. also, a file so opened gains the attribute 'newlines'; the value for this attribute is one of None (no newline read yet), '\ R',' \ n ', '\ r \ n' or a tuple containing all the newline types seen.

Open the file. The default value is reading mode (r). The mode parameter can be 'r'-reading, 'w'-writing or 'A'-appending (append ). If it is in writing mode or appending mode, it may be created if the file does not exist. The file may be truncated in writing mode. 'B' mode is used for binary files. The '+' mode allows simultaneous file read and write.

Buffering: 0, no buffer; 1, one row of buffer. The larger the number, the larger the buffer.

The built-in function open () is recommended for opening files (). In 'U' mode, you can enter a line break to open a file. In Python, any row Terminator is treated as '\ n' in the input file '. In addition, the 'newlines' attribute is added to the file. The value of this attribute is None (when no new lines are readable), 'R', 'n ', '\ r \ n' or a tuple contains the types of all linefeeds.

| 'U' cannot be combined with 'W' or '+ 'mode.
| 'U' cannot be used with 'W' or '+.
Methods defined here: | close (...) | close ()-> None or (perhaps) an integer. Close the file.
| Close a 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.

Set the data property. closed () to true. The closed file cannot be used for further I/O operations (you cannot close the file )! If no error occurs, it can be called more than once. Some types of file objects may return a state value when they are closed (for example, a file object opened by popen ). [Note: OS. popen ()]

| Fileno (...)

| Fileno ()-> integer "file descriptor ".
| The returned value is an integer (file descriptor)
| This is needed for lower-level file interfaces, such OS. read ().
| Requires a low-level file interface, such as OS. read ()
| Flush (...) | flush ()-> None. Flush the internal I/O buffer writes the buffer content to the disk! (Used after write)
| Isatty (...) | isatty ()-> true or false. true if the file is connected to a tty device. whether the returned file is a terminal device file [used in unix ].
| Next (...) | x. next ()-> the next value, or raise StopIteration [that is, the generator method. Return the next row .]
|
| Read (...) | read ([size])-> read at most size bytes, returned as a string.
| Reads data and returns a string. The size can be specified.

| 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.

If the size is negative or the default value, read the entire file. Note that in non-blocking mode, data may return less than the actual request. The timely size parameter is not specified (that is, the default status )!

| Readinto (...) | readinto ()-> uninitialized ented. Don't use this; it may go away.
|
| Readline (...) | readline ([size])-> next line from the file, as a string.
| Reads the next row of the file and returns 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.

Keep new rows. The non-negative size parameter limits the maximum number of bytes returned (that is, incomplete rows may be returned ). An empty string is returned when the file ends!

| Readlines (...) | readlines ([size])-> list of strings, each a line from the file.
| Returns the string list of each row of data
| 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. call the readline () method constantly and return a list composed of each row of data (str. [List (f) has the same effect. The size parameter 2.7.6 has not changed. It is the same as that read by read () and will be further determined .]
| Seek (...) | seek (offset [, whence])-> None. Move to new file position.
|
| Argument offset is a byte count. optional argument whence ults to 0 (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.

| Move the operation mark of the file to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. However, if the whence parameter is provided, it is not necessary. If the whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the Operation mark of the file is automatically returned to the end of the file each time the file is written.

| Tell (...) | tell ()-> current file position, an integer (may be a long integer ).
| Returns the current position of the file, an integer (which may be a long integer ). [That is, when a row reads and writes a file, the current cursor position (starting with a file )]
| Truncate (...) | truncate ([size])-> None. Truncate the file to at most size bytes. truncate the file by size.
|
| Size defaults to the current file position, as returned by tell (). [Description is too simple to be determined]
|
| Write (...) | write (str)-> None. Write string str to file.
| Writes a string to a file. The returned value is None.
| Note that due to buffering, flush () or close () may be needed before the file on disk reflects the data written. only after flush () or close () is executed can the file be truly written.
| Writelines (...) | 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. Note that no new lines are added. Sequence_of_strings can be an iterator composed of strings. This is equivalent to calling write () to write each string. [Line breaks are not automatically generated, that is, line breaks are not automatically added. sequence_of_strings can be used to set list, tuple, and dict (keep the content in the iterator as str ).]
| Xreadlines (...) | xreadlines ()-> returns self.
| Returns itself
| For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. backward compatible. File objects include the xreadlines module previously implemented for performance optimization.
|

| ----------------------------------------------------------------------

File read/write 1, common type
>>> F = open ("C: \ Users \ admin \ Desktop \ 222.txt", 'R') >>> print f. read () @ The Third Wave (Blog address: http://blog.csdn.net/zhanh1218) File read and Write! >>> F. closedFalse >>> f. close () >>>> f. closedTrue >>>
After reading the file, you must close () to close the object. After the file is used, it must be closed because: The file object occupies the resources of the operating system, and the number of files that can be opened at the same time in the operating system is limited. Ii. try -- try t -- finally
>>> Try: f = open ("C: \ Users \ admin \ Desktop \ 222.txt", 'R') print f. read () print f. closedexcept: print "error" raisefinally: if f: f. close () print f. closed @ The Third Wave (Blog address: http://blog.csdn.net/zhanh1218) File Read and Write! FalseTrue >>>
Very troublesome! 3. Use the with as statement in literature and art. Recommended !!!
>>> With open ("C: \ Users \ admin \ Desktop \ 222.txt", 'R') as f: print f. read () print f. closed @ The Third Wave (Blog address: http://blog.csdn.net/zhanh1218) File Read and Write! False >>> f. closedTrue >>>

 

This article by @ The_Third_Wave (Blog address: http://blog.csdn.net/zhanh1218) original. Update from time to time. If any error occurs, please correct it.

Sina Weibo follow :@The_Third_Wave

If this blog post is helpful to you, you are not recommended to repost it for a good network environment. We recommend that you add it to your favorites! If you must reprint the content, please include the suffix and the address of this 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.