The files are divided into text files and binary files according to the organization of the data in the files.
Text file: A text file stores regular strings, consisting of several text lines, each line usually ends with a newline '\n'.Regular strings refer to strings that Notepad or other text editors can display and edit normally and that humans can directly read and understand, such as English letters, Chinese characters, and numeric strings.Text files can be edited using word processing software such as gedit, notepad.
Binary file: The binary file stores the object content as a byte string (bytes), which cannot be edited directly with Notepad or other common word processing software, and usually cannot be directly read and understood by humans, requiring the use of special softwareRead, display, modify or execute after decoding.Common ones such as graphic image files, audio and video files, executable files, resource files, various database files, various office documents, etc. are all binary files
Three steps for file content operation: Open, read and write, close.
open(file, mode='r', buffering=-1, encoding=None, errors=None,newline=None, closefd=True, opener=None)The file parameter specifies the name of the file to be opened.The mode parameter specifies how the file is processed after opening.The buffering parameter specifies the buffering mode for reading and writing files.0 means no cache, 1 means cache, and if it is greater than 1, it means the size of the buffer.The default value -1 means that the cache is managed by the system.The encoding parameter specifies the way to encode and decode the text. It is only applicable to text mode, and any format supported by Python can be used, such as GBK, utf8, CP936, etc.
If the execution is normal, the open() function returns a file object, through which the file can be read and written.
If the specified file does not exist, access rights are insufficient, disk space is insufficient, or other reasons cause the creation of the file object to fail, an exception is thrown.
f1 = open('file1.txt', 'r') # open the file in read modef2 = open('file2.txt', 'w') # open the file in write mode
When you are done with the contents of the file, be sure to close the file object, so as to ensure that any modifications made are indeed saved to the file.
f1.close()
However, even if the code to close the file is written, there is no guarantee that the file will close properly.For example, if an error occurs after opening the file and before closing the file and the program crashes, the file cannot be closed properly.It is recommended to use with keyword when managing file objects, which can effectively avoid this problem.
with open(filename, mode, encoding) as fp:#Here write the statement to read and write the content of the file through the file object fp
The context management statement with also supports the following usages:
with open('test.txt', 'r') as src, open('test_new.txt', 'w') as dst:dst.write(src.read())
Open file with:
Mode
Description
r
Read mode (default mode, can be omitted), throw an exception if the file does not exist
w
Write mode, if the file already exists, clear the original content first
x
Write mode, create new file, throw exception if file already exists
a
Append mode, do not overwrite the original content in the file
b
Binary mode (can be combined with other modes)
t
Text mode (default mode, can be omitted)
+
Read, Write mode (can be combined with other modes)
File Object Common Properties
Properties
Description
buffer
Returns the buffer object of the current file
closed
Determine whether the file is closed, if the file is closed, return True
fileno
File number, generally don't care too much about this number
mode
Returns the open mode of the file
name
returns the name of the file
Example 7-1 writes to a text file and then reads it out.s = 'Hello world\nText file reading method\nText file writing method\n'with open('sample.txt', 'w') as fp: #Use cp936 encoding by defaultfp.write(s)with open('sample.txt') as fp: #Use cp936 encoding by defaultprint(fp.read())
Example 7-3 reads and displays all lines of a text file.with open('sample.txt') as fp: #Assume the file is encoded in CP936for line in fp: #The file object can be iterated directlyprint(line)