Python File Processing pointer (4 ),
The content of the response. The first object is returned, and the second object is returned ''. It cannot be read repeatedly. What if I want to read it again? How to solve the problem.
In fact, this is related to the file pointer. When we operate on the file, there will be a file pointer inside the file to locate the current location,
When open is enabled, the file pointer is at the initial position 1. When the 4-byte content is read, the file pointer is at the file pointer position 4. When the write operation is performed, the file pointer is moved from 4 to 8. Therefore, as long as the file pointer is controlled, you can read it again!
You can use the seek method to manipulate file pointers:
Seek (offset, whence): Move the file pointer
Offset: offset, which can be a negative number.
Whence: relative offset position
The relative offset is SEEK_SET, SEEK_CUR, and SEEK_END in the OS module:
OS. SEEK_SET: indicates the relative start position of the file.
OS. SEEK_CUR: indicates the relative current location of the file.
OS. SEEK_END: indicates the relative end position of the file.
Refer to the authorization code (blogCblog content is contained in a blogcblog.txt file ):
1 f = open('blogCblog.txt ') # first create a file object 2 print f. read (3) # Use the read () method to read and print 3 print f. tell () # print the position of the file pointer 4 f. close () # close the File 5 6 # print the result: blo7 #3
As shown above, read (3) is used to read 3 bytes, while the tell () method returns the position of the file pointer. The file pointer is as follows:
1 import OS # import OS module 2 f = open('blogCblog.txt ') # first, create a file object. The open method is w 3 print f. read (3) # Use the read () method to read and print 4 print f. tell () # print the position of the file pointer 5 f. seek (0, OS. SEEK_SET) # Use the seek () method to operate the file pointer (move the file pointer to the starting position of the file and move 0) 6 print f. read (3) # read again and print 7 print f. tell () # print the position of the file pointer 8 f. close () # close file 9 10 # print the result: blo11 #312 # blo13 #3
The above code is read again. If you comment out the fifth line, the output of lines 6th and 7 is gCb and 6, because the file pointer is 3rd, when reading the file again, the pointer of the current file is moved back. That is why readline () remembers the reading position. The role of the 5th line of code is to move the file pointer to the initial position! The read is repeated.
When you move the pointer, IOError is reported when the offset is greater than the string length!