SoFunction
Updated on 2024-11-17

A guide to the use of open in python.

open

Python provides very convenient functions for reading and writing files, where theopenis the first step in reading and writing files through theopenReading and writing files is the same as putting an elephant in a refrigerator.

f = open("",'w')    # First step, open the refrigerator door (file) #
("this is content")  # Step 2, load the elephant (file contents) in
()                   # Step three, close the refrigerator door or the elephant may run away #

openis defined in such a way that

file=open(path,mode='r',buffering=-1,encoding=None)

Among them.

  • pathis the file path
  • modeis the read mode, which defaults tor, i.e., read-only mode.
  • bufferingis the buffer, because the memory reads and writes faster than the peripheral, so most cases do not need to set, that is, not greater than 0.
  • encodingcoding scheme
  • Finally, the output of thefileIt's a file.boyfriend

Among them.modeThese include the following

r r+ w w+ a a+
b rb rb+ wb wb+ ab ab+

where b denotes binary, r denotes read, w denotes write, and a denotes append. Regardless of the mode, there are+Then it means readable and writable. Writes generally overwrite the original file, and appends start at the end of the original file. If the file does not exist, thew, w+, a, a+, wbA new file will be created.

file object

pass (a bill or inspection etc)openfile object created, except for the one used to close the file'scloseOutside of that, there are two groups of the most commonly used functions, the ones that represent read and writereadcap (a poem)writeThe differences are as follows

read write Read and write the entire file
read(size) reads a file of size.
readline Read one line at a time.
Since write inputs a string directly, there is no need to set up a writeline.
readlines writelines The former reads the file on a line-by-line basis and stores it in a list of strings
writelines writes a list of strings to a file.

for example

>>> f = open('','w')
>>> (['a','b','c\n','d'])
>>> ()
>>> f = open('','r')
>>> ()
['abc\n', 'd']      #When writing lines, it doesn't automatically add \n
>>> ()

According to the performance of my computer, reading 500M txt will be more than 1s, reading 2G files are most likely to report an error. This time you need to passseekfunction to specify the offset, and then read and write operations are performed on the file at the location of the offset. Its input is the(offset,whence=0)

included among these

  • offsetis the offset
  • whenceis the offset mode, when it is 0, it means absolute positioning; when it is 1, it means relative positioning; when it is 2, it means positioning from the end.

through (a gap)seekperspective.openfile, if you use thewand the other represents theseek(0)If you use theaand the other represents theseek(0,2)

pass (a bill or inspection etc)tellcan return the current offset, which is equivalent to theseekThe pairwise function of the

At the end of the operation on the file, you need to use the()writes the cached string to the hard disk; if you're afraid of surprises, you can use the()Forced Write.

In addition, the member variables of the file object are as follows

name mode encoding error closed buffer
filename read-write mode coding method error mode Is it closed buffer

In addition there are three decision functions

readable() writable() seekable
readable Writable Can an offset be specified

with ... as expression

When writing to a file, if you forget tocloseorflush, then there may still be some data left in memory, which causes the file we get to be mutilated.

with asExpressions can be created by calling the__enter__methodology and__exit__method to make smarter calls to thecloseThis eliminates the need to forget to writecloseof trouble. Its invocation method is

with open('','w') as f:
    ("12345")

ferret outits__exit__The function is exactlyclose:

def __enter__(self):
    return self

def __exit__(self, type, value, traceback):
    ()

Underlying implementation.

openis very convenient function, but the overhead is also very large, after all, directly returned a file object. In contrast, the underlying implementation ofThe return is an integer file ID, which can be considered for frequent file read and write operations where speed is important.

osThe method to open a file in

fd = (path, flags, mode=511, dir_fd=None)

Among them.

  • pathis the file path
  • flagsis an open flag, e.g.os.O_RDONLYRepresents read-only,os.O_WRONLYRepresents write-only
  • modeIndicates file permissions, for example, 777 means that anyone can read, write and execute; 511 means that the creator of the file can read and execute it, and others can only execute it, which belongs to Linux, and can be said specifically in Linux later.
  • dir_fdThe rules for relative paths, which are customized functions and less frequently used.
  • Finally, the output of thefdis an identifier for a particular file.

where the value of mode can be found indeepincap (a poem)windowsmanual, the commonly used flags are as follows, and multiple flags can be used via the|Superimposed, this strong C wind confirms that it comes from the OS without a doubt.

open open
os.O_RDONLY ‘r’ os.O_WRONLY ‘w’
os.O_RDWR ‘r+’ os.O_APPEND ‘a’
os.O_CREAT Create and open

Among the related functions are:

(fd, mode, bufsize) Creates a file object via fd and returns this file object
(fd, n) Reads up to n bytes from fd and returns them, or an empty string if fd has reached the end of the file.
(fd, str) Write str to fd, return the length of the actual string written
(fd) Forces the file corresponding to fd to be written to the hard disk.
(fd) Close fd
(fd) Copy fd
os.dup2(fd, fd2) Copy the file corresponding to fd1 to fd2
(fd) Returns the status of fd
(fd, length) Crop fd, length not larger than file size
(fd) Returns True if fd is already open and also connected to a tty(-like) device, False otherwise.
(fd, pos, how) Set the current position of fd to pos, how is the mode of modification, which is equivalent to whence in the previous section.

to this article on the use of python open usage guide to this article, more related to the use of python open content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!