1: #r模式, a new file is not created when the file does not exist
f = open (' A.txt ', ' r ', encoding = ' utf-8 ')
2: Character encoding
What is character encoding?
Translate human characters into numbers that computers can recognize
What is a character encoding table?
Ascii
GBK
UTF-8
Unicode
Unicode-------->encode (' utf-8 ')-------------->bytes
Bytes------------>decode (' utf-8 ')--------------->unicode
Principle:
What format the character is compiled in and what format it will decode
Ps:
The characters in Python3 are divided into two types
x= ' Egon ' into Unicode
Y=x.encode (' Utf-8 ') saved into bytes
The strings in Python2 are also divided into two types
x = U ' Egon ' is the same as the string in Python3
Y= ' Alex ' is the same as the bytes type in Python3
#r模式的读, does not create a new file when the file does not exist
F = open (' A.txt ', ' r ', encoding = ' utf-8 ')
Print (F.read ())
F.close ()
#b模式即直接从硬盘中读取bytes
Print (F.read () decode (' Utf-8 ')
#w文本模式的写, file exists is empty, does not exist create
F = open (' A.txt ', ' W ') , encoding = ' utf-8 ')
F = open (' B.txt ', ' w ', encoding = ' utf-8 ')
Print (f.writeable ()) #判断是否可写
Print (f.readable ( ) #判断是否可读
#a文本模式的追加
F = open (' B.txt ', ' a ', encoding = ' utf-8 ')
Print (f.writeable ()) #写文件涉及到文件光标的移动
Print (F.tell ())
Print (F.readline ())
F.write (' 333\n ')
#r +,w+,a+, can be written when read, can be read when writing
# RB mode reads directly from the hard drive bytes
F = open (' a.txt ', ' RB ')
Print (F.read (). Decode (' Utf-8 '))
#wb模式
F = open (' A.txt ', ' WB ')
F.write (' Hello '. Encode (' Utf-8 ')
# #b模式可以读取任何模式的文件
with open (' test.jpg ', ' RB ') as Read_f,\
O Pen (' test1.jpg ', ' WB ') as Write_f:
for line in Read_f:
Write_f.write (line)
####### ###################################################
f = open (' A.txt ', ' r ', encoding = ' utf-8 ')
Print (F.read ())
#f. Read () can specify multiple, read as text, in characters
f = open (' a.txt ', ' RB ')
Print (F.read (3). Decode (' Utf-8 '))
#以字节为单位, 1 Chinese accounts for 3 bytes, in text mode, read in characters, in B mode, in bytes, the rest of the files within the cursor movement are in bytes
f = open (' A.txt ', ' r ', encoding = ' utf-8 ')
Print (F.read ())
F.seek (0) #表示将光标的位置移动到开头
Print (F.read ())
F.seek (1) #表示从第一个字符开始读取
Print (F.tell ()) #tell表示以字节显示的
F.seek (6,0) #代表从文件开头取6个字节, according to the read mode, if it is readable mode, the character is read, the other reads the byte
F.seek (6,1) #以当前光标所在的位置为参照物
#seek有3种移动方式0, 1 and 2 must be in B mode, and 0 can be used in text mode
f = open (' a.txt ', ' RB ')
F.seek (0,2) #此时光标一直指向最后
F.seek ( -1,2) #倒着切一个字节
CP text
1 ## # #文件习题2 Import Time3With open ('Test.txt','RB') as F:4 f.seek (0)5 whileTrue:6line =F.readline ()7 ifLine :8 Print(Line.decode ('Utf-8'), end="')9 Else:TenTime.sleep (0.5)
Python development "Article xxx" file operation----Review