1. File read and write operations
Read-write files are the most common IO operations, and Python has built-in functions for reading and writing files.
The ability to read and write files on disk is provided by the operating system, so read-write files are requested by the operating system to open a file object (often referred to as a file descriptor) and then read the data from the file object via an interface provided by the operating system, or write the data to the file object.
How files are opened
Open (file, mode= ' R ', Buffering=none, Encoding=none) Opening function opens a file: Open file directory path mode: Open file mode, read and write; buffering: Buffer Buffering size encoding: Open in what format, Common: Utf-8, GBK
Full list of open files in different modes:
2. Properties of the File object
After a file is opened, you have a files object that you can get various information about the file.
The following is a list of all properties related to the file object:
f = open (' Test.txt ', ' R ', encoding= ' Utf-8 ') print (' File name: ', f.name) print (' Is closed: ', f.closed ') print (' Access mode: ', F.mode) # Execution Result: # File Name: test.txt# is closed: false# access mode: R
3. Document positioning
(1) Tell
Gets the current cursor position of the file being opened
f = open (' Test.txt ', ' R ', encoding= ' utf-8 ') str1 = F.read (8) print (str1) print (' Cursor current position: ', F.tell ()) f.close () # Execution Result: # abcdefgh# cursor Current Position: 8
(2) Seek (offset [, from])
Changes the position of the current cursor, and the offset variable represents the number of bytes to move
The from variable specifies the reference position at which to begin moving bytes
From=0 the beginning of the file as a reference for moving bytes
From=1 using the current position as the reference location
from=2 the end of the file as the reference location
f = open (' Test.txt ', ' R ', encoding= ' Utf-8 ') # The Read method reads the number of characters, not the number of bytes str1 = f.read (8) print (' "Read the first 8 characters:" ', str1) print (' " Position of the current cursor (in bytes): "', F.tell ()) # Use the Seek method to set the cursor to the beginning of the file F.seek (0, 0) print ('" The position of the current cursor (in bytes): "', F.tell ()) print ('" reads all contents of the file: " ', F.read ()) # Execution Result: # "reads the first 8 characters:" Where the Rainbow tells me # "The position of the current cursor (in bytes):" 24# "the position of the current cursor (in bytes):" 0# "reads all the contents of the file:" Where's the Rainbow tell me if I can give my wish back
The operating unit of the method that operates on the contents of the file:
Based on the various patterns, summarize the following (+ indicates the specific actions that the pattern can use):
Reference Documentation:
Http://www.runoob.com/python/python-files-io.html
Read and write operations for [Python] Files