Python_復習1
阿新 • • 發佈:2017-07-16
python2 alex size read ada utf-8 字符串 write nco
1:#r模式,在文件不存在時,不會創建新的文件
f = open(‘a.txt‘,‘r‘,encoding = ‘utf-8‘)
2:字符編碼
什麽是字符編碼?
把人類的字符翻譯成計算機能認識的數字
什麽是字符編碼表?
ASCII
GBK
UTF-8
Unicode
unicode-------->encode(‘utf-8‘)-------------->bytes
bytes------------>decode(‘utf-8‘)--------------->unicode
原則:
字符以什麽格式編譯的,就要以什麽格式解碼
ps:
python3中的字符分為兩種
x=‘egon‘存成unicode
y=x.encode(‘utf-8‘)存成bytes
python2中的字符串也分成兩種
x = u‘egon‘ 與python3中的字符串相同
y=‘alex‘與python3中的bytes類型相同
#r模式的讀,在文件不存在時,不會創造新的文件
f = open(‘a.txt‘,‘r‘,encoding = ‘utf-8‘)
print(f.read())
f.close()
#b模式即直接從硬盤中讀取bytes
print(f.read().decode(‘utf-8‘))
#w文本模式的寫,文件存在則清空,不存在則創建
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+,代表讀的時候可以寫,寫的時候可以讀
#rb模式即直接從硬盤中讀取bytes
f = open(‘a.txt‘,‘rb‘)
print(f.read().decode(‘utf-8‘))
#wb模式
f = open(‘a.txt‘,‘wb‘)
f.write(‘你好啊‘.encode(‘utf-8‘))
##b模式可以讀取任何模式的文件
with open(‘test.jpg‘,‘rb‘) as read_f,\
open(‘test1.jpg‘,‘wb‘) as write_f:
for line in read_f:
write_f.write(line)
Python_復習1