In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how to read and write documents in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Open
Python provides a very convenient function for reading and writing files, in which open is the first step in reading and writing documents. Reading and writing files through open is the same as putting an elephant in a refrigerator.
F = open ("test.txt",'w') # first step, open the refrigerator door (file) f.write ("this is content") # second step, put the elephant (file content) into f.close () # third step, close the refrigerator door, otherwise the elephant may run away
Open is defined as
File=open (path,mode='r',buffering=-1,encoding=None)
Among them
Path is the file path
Mode is read mode, and the default is r, that is, read-only mode.
Buffering is a buffer, because the read and write speed of memory is faster than that of peripherals, so most cases do not need to be set, that is, no more than 0.
Encoding is the encoding mode.
Finally, the output file is a file object.
Among them, mode includes the following
Rr+ww+aa+brbrb+wbwb+abab+
Where b stands for binary, r for read, w for write, and a for append. No matter what the mode, having + means being readable and writable. Writing generally overwrites the original file, and appending starts at the end of the original file. If the file does not exist, w, w, a, a, wb will create a new file.
File object
For file objects created through open, in addition to the close used to close the file, there are two most commonly used sets of functions, namely read and write, which represent read and write, respectively. The differences are as follows
Readwrite reads and writes the entire file
Read (size) can read the file readline of size size
Read one line at a time
Because write inputs strings directly, it is not necessary to set writelinereadlineswritelines to read files by line and store a list of strings
Writelines writes a list of strings to the file
For example
> f = open ('test.txt','w') > > f.writelines > f.close () > > f.close () > > f = open (' test.txt','r') > f.readlines () [\ n > f.close () is not automatically added when writing lines
According to the performance of my computer, reading 500m txt will take more than 1 second, and reading 2G files will mostly report an error. At this point, you need to specify the offset through the seek function, and then read and write the file at the location of the offset. Its input is f.seek (offset,whence=0)
Among them
Offset is offset
Whence is offset. A value of 0 indicates absolute positioning, 1 indicates relative positioning, and 2 indicates positioning from the end.
From seek's point of view, if w is used in open files, it stands for seek (0), and if an is used, it represents seek (0mem2).
Through tell, you can return the current offset, which is equivalent to the dual function of seek.
At the end of the operation on the file, you need to use f.close () to write the cached string to the hard disk; if you are afraid of an accident, you can use f.flush () to force the write.
In addition, the member variables of the file object are as follows
Namemodeencodingerrorclosedbuffer file name read-write mode encoding error mode whether the buffer has been closed
In addition, there are three decision functions
Whether readable () writable () seekable is readable or writable can specify offset with. As expression
If you forget close or flush when writing to a file, there may be some data left in memory, causing the file we get to be incomplete.
With as expressions can call close more intelligently by calling the _ _ enter__ method and the _ _ exit__ method in the object, thus eliminating the hassle of forgetting to write close. Its calling method is
With open ('text.txt','w') as f: f.write ("12345")
If you look at file.py, its _ _ exit__ function is close:
Def _ _ enter__ (self): return selfdef _ exit__ (self, type, value, traceback): self.close () underlying implementation: os.open
Open is a very convenient function, but it is also very expensive, after all, it returns a file object directly. By contrast, its underlying implementation, os.open, returns an integer file ID, which can be considered for frequent file read and write operations that require speed.
In os, the method to open a file is
Fd= os.open (path, flags, mode=511, dir_fd=None)
Among them
Path is the file path
Flags is the open flag, for example, os.O_RDONLY stands for read-only, os.O_WRONLY stands for write-only
Mode represents file permissions, for example, 777 represents anyone who can read, write and execute; 511 represents the creator of the file can read and execute, others can only read, this belongs to the content of Linux, can be specifically said in Linux in the future.
Dir_fd represents the rule of relative path, which is a custom function and is rarely used.
Finally, the output fd is the identity of a file.
Among them, the value of mode can be found in the manuals of deepin and windows. The commonly used signs are as follows. Multiple signs can be superimposed by |. This strong C wind confirms that it comes from the operating system.
Os.openopenos.openopenos.O_RDONLY'r'os.O_WRONLY'w'os.O_RDWR'r+'os.O_APPEND'a'os.O_CREAT creates and opens
The related functions include:
Os.fdopen (fd, mode, bufsize) creates a file object through fd and returns the file object os.read (fd, n) reads up to n bytes from the fd and returns, and returns an empty string if the fd corresponding file has reached the end. Os.write (fd, str) writes str to fd, returns the actual written string length os.fsync (fd) forces the file corresponding to fd to be written to the hard disk os.close (fd) turns off fdos.dup (fd) copies fdos.dup2 (fd, fd2) copies the file corresponding to fd1 to fd2os.fstat (fd) returns the status of fd os.ftruncate (fd, length) clips fd, length is not greater than the file size os.isatty (fd) if fd has been opened If it is connected to a tty (- like) device at the same time, it returns True, otherwise False. Os.lseek (fd, pos, how) sets the current location of fd to pos, and how for modification, which is equivalent to the previous whence "how to read and write files". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.