Open file for file operation

Source: Internet
Author: User

First, open the file

obj = open (' File path ', ' Open file Mode ')

Open file methods are:

R: Read-only mode

r+: equivalent to RW

W: Write Method

w+: Still equals W, meaningless

A: Append method

A +: Still equals a, meaningless

Open () is a python built-in function that provides a common interface for initializing input/output (I/O) operations, returning an object after successfully opening a file, or IOError exception, file () is a factory function, which, like the open method, can be interchanged, However, open () is generally recommended because open () is a python built-in function. Late file will be merged into other functions


Introduce two methods:

Obj.tell ()

Tell returns the current position of the read/write pointer before or after reading the file. (In other words, tell you where the pointer is)

Obj.seek ()

Sets the current position of the file at offset. The parameter is optional 0 to move to an absolute position (starting from the beginning of the file),
1 means move to a relative position (from the current position)

The sample code is as follows:

obj = open (' log.py ', ' R ')
Obj.seek (5)----------> position the pointer to the 5th byte position after opening the file to facilitate the next operation
Print Obj.tell ()-------> Prints the position of the pointer. (Read starting at 5 byte positions)
Print obj.read ()-------> Print read file to last
Print Obj.tell ()-------> printing pointer to position
Obj.close ()---------> Close File

log.py content is as follows:

11111111
222222


Output Result:
5
111
222222
16


Open File as r+ form

The sample code is as follows:

__author__ = ' Ryan '
obj = open (' log.py ', ' r+ ')
Print Obj.tell ()
Obj.write (' ########## ')
Obj.close ()

log.py content is as follows
11111111
22222222

Execute the above code to view log.py content

######### #2222222

The description is opened in r+ mode, when writing content, if directly from the location at the beginning of the file (that is, 0 position) then the previous content will be overwritten from the 0 position, the number of written content will be overwritten;


Look at the following code, move the pointer position to the 8th byte position, and then execute the write *

__author__ = ' Ryan '
obj = open (' log.py ', ' r+ ')
Print Obj.seek (8)

Print Obj.tell ()

Obj.write (' ************* ')
Obj.close ()

View log.py Results

########*************

Write an asterisk (*) starting from the 8th position

Then look at the next piece of code: (Add the Truncate ()) method to the above code, and restore the pointer to the beginning of the file (i.e. 0 position)

__author__ = ' Ryan '
obj = open (' log.py ', ' r+ ')
Print Obj.tell ()

Obj.write (")

Obj.truncate ()

Obj.close ()

Re-observation of log.py content is as follows:

@@@@@@

All content after 5 @ sign is found, all content after 5 @ symbol is intercepted

And then look at the following code:

obj = open (' log.py ', ' RB ')
Print Obj.tell ()
Obj.write (")
Obj.truncate ()
Obj.close ()


Where ' RB ' is a binary way to read files, if cross-platform is to add B, because the Linux files are stored in binary. On Windows, you need to add a B


Summary:

When working with files, you typically need to go through the following steps:

Open File
Manipulating files

First, open the file
1

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

Note: There are two ways to open a file in Python, that is, open (...) and file (...), which, in essence, calls the latter in order to manipulate files, and it is recommended to use open.

When you open a file, you need to specify the file path and how you want to open the file, and then open it to get the file handle and manipulate it later through the file handle.

the mode of opening the file is:

R, read-only mode (default).
W, write-only mode. "unreadable; not exist; create; delete content;"
A, append mode. "Readable; not exist" create; "only append content;"

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

r+, can read and write files. "readable; writable; can be added"
w+, write and read
A +, with a

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

RU
R+u

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

Rb
Wb
Ab

second, the operation of the document

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 ())
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__
flush File internal buffers
"" "Flush (), None. Flush the internal I/O buffer. """
Pass


def isatty (self): # real signature unknown; Restored from __doc__
determine if the file is a consent 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, then an error
"" "X.next (), the next value, or raise Stopiteration" ""
Pass

def read (self, size=none): # Real signature unknown; Restored from __doc__
reads the 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 at non-blocking mode, less data than what is requested
May is 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__
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 (a incomplete line is 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 a list of values based on line breaks
"""
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 a 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__
specify pointer position in file
"""
Seek (offset[, whence]), None. Move to new file position.

Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should is >= 0); Other values is 1
(move relative to current position, positive or negative), and 2 (move
Relative to end of file, usually negative, 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 ()-current file position, an integer (may be a long integer)." "
Pass

def truncate (self, size=none): # Real signature unknown; Restored from __doc__
truncate data, preserving only the previous data specified
"""
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 a 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; Restored from __doc__
can be used to read files line by row, not all
"""
Xreadlines (), returns self.

For backward compatibility. File objects now include the performance
Optimizations previously implemented in the Xreadlines module.
"""

Pass

This article from "Flat Light is true" blog, please be sure to keep this source http://cryan.blog.51cto.com/10837891/1719393

Open file for file operation

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.