Python_ Review 1

Source: Internet
Author: User

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模式的读, no new files are created 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文本模式的写, the file exists is emptied, does not exist and is created
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+, it can be written when read, can be read when written.

#rb模式即直接从硬盘中读取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,\
open (' test1.jpg ', ' WB ') as Write_f:
For line in Read_f:
Write_f.write (line)

Python_ Review 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.