My friends, for reprint please indicate the source: blog.csdn.net/jiangjunsho…

Disclaimer: During the teaching of artificial intelligence technology, many students asked me some python related questions, so in order to let students master more extended knowledge and better understand AI technology, I asked my assistant to share this Python series of tutorials, hoping to help you! Since this Python tutorial is not written by me, it is not as funny and boring as my AI teaching. But its knowledge points or say in place, also worth reading! PS: if you don’t understand this article, please read the previous article first. Step by step, you won’t feel difficult to learn a little every day!

Let’s look at a simple example of file manipulation. First open a new file in output mode, write a string (terminated with line terminator \n), and then close the file. Next, we open the same file again in input mode and read the line. Notice that the third readline call returns an empty string. This indicates that the bottom of the file has been reached (the empty lines of the file are strings containing newlines, not empty strings) :

>>> myfile = open ('myfile.txt','w') # open for text output: Create /empty >>> myfile.write ('hello text file\n') # write a line of text: String 16 >>> myfile.write ('goodbye text file\n') 18 >>> myfile.close () # Flush output buffers to disk >>> myfile = Open ('myfile.txt') # open for text input: 'r' is default >>> myfile.readline () # Read the lines back 'hello text file\n' >>> myfile.readline () 'goodbye text File \n' >>> myfile.readLine () # Empty String: end of file 'Copy the code

The above example writes a line of text as a string, including the line terminator \n. Note that the write method does not add a line terminator for us, so the program must include it to strictly terminate the line (otherwise, the next write will simply prolong the file’s current).

We can also use the file object’s read method to read the entire file into a string:

>>> open ('myfile.txt').read () # read all at once into string 'hello text file ngoodbye text file n' >>> Print (open ('myfile.txt').read ()) # user-friendly display hello text file Goodbye text fileCopy the code

If you want to iterate through a text file line by line, file iterators are often the best option:

>>> for line in open ('myfile') : # Use file iterators,not reads... Print (line,end= ")... hello text file goodbye text fileCopy the code

When a file is read as a file iterator, the temporary file object created by Open will automatically read in and return a line at each iteration of the loop. This form is usually easy to write and is fast and memory efficient.