Codec operation
Byte byte, a byte consists of 8 bit components.
Encoding process, the byte stream character to encode
Decoding process by the byte stream into character decode
What format encoding, decoding is necessary what format
Open the file in three modes
1, r mode,
Read-only, if the file does not exist will complain
2, w pattern
Write only if the file does not exist, create a file, write content
If the file exists, the first file of the contents emptied and the contents written into
3, a pattern
If the file exists, then later append content
If the file does not exist, create a file, write content
Open the file syntax:
Open with ( R & lt ' with the suffix of the file name ', mode = ' open mode ', encoding = ' encoding format file ') AS F :
r: the escape character is used to escape 'file name with the suffix' path
File name with the suffix: it can be an absolute path, or a relative path
File encoding format: file with the same coding mode can be opened
f: file objects built, to facilitate later using
for example:
with open(r'RECORD.txt', 'w', encoding='utf-8') as wf: wf.write('AAAAAAA') # AAAAAAA with open(r'RECORD.txt', 'a', encoding='utf-8')as af: af.write('BBBBB') # AAAAAAABBBBB
You can also open two simultaneous text file , a read a write-only
with open (r'RECORD.txt ',' r ', encoding =' utf-8 ') as rf, \ default when #r rt, read the text file open (r'newRecord.py', 'w' , = encoding 'UTF-. 8') AS WF: A = rf.read () # open file RECORD.txt wf.write (a) # the file is written newRecord.py RECORD.txt
Open pictures and other non-text files , copy when not specified encoding parameters.
with open (r'th.jpg ',' rb ') as rf, open (r'newPhoto.png', 'wb') as wf: #rb byte file for reading sss = rf.read () WF. write (sss)