open
Python provides very convenient functions for reading and writing files, where theopen
is the first step in reading and writing files through theopen
Reading 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 #
open
is defined in such a way that
file=open(path,mode='r',buffering=-1,encoding=None)
Among them.
-
path
is the file path -
mode
is the read mode, which defaults tor
, i.e., read-only mode. -
buffering
is 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. -
encoding
coding scheme - Finally, the output of the
file
It's a file.boyfriend。
Among them.mode
These 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+, wb
A new file will be created.
file object
pass (a bill or inspection etc)open
file object created, except for the one used to close the file'sclose
Outside of that, there are two groups of the most commonly used functions, the ones that represent read and writeread
cap (a poem)write
The 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 passseek
function 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
-
offset
is the offset -
whence
is 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)seek
perspective.open
file, if you use thew
and the other represents theseek(0)
If you use thea
and the other represents theseek(0,2)
。
pass (a bill or inspection etc)tell
can return the current offset, which is equivalent to theseek
The 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 toclose
orflush
, then there may still be some data left in memory, which causes the file we get to be mutilated.
with as
Expressions can be created by calling the__enter__
methodology and__exit__
method to make smarter calls to theclose
This eliminates the need to forget to writeclose
of 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.
open
is 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.
os
The method to open a file in
fd = (path, flags, mode=511, dir_fd=None)
Among them.
-
path
is the file path -
flags
is an open flag, e.g.os.O_RDONLY
Represents read-only,os.O_WRONLY
Represents write-only -
mode
Indicates 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_fd
The rules for relative paths, which are customized functions and less frequently used. - Finally, the output of the
fd
is 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!