Other character encoding applications and files - Python development foundation day10 python knowledge base: the first stage

Recap last lesson

Copy depth

Depth copies only for variable types

copy

lt = [1,2,3[4,5,6]]
lt2 = lt
# 当lt2 为lt的拷贝对象时,lt内部任意数据数据类型的 对象变化,lt2都变化

Shallow copy

import copy
lt = [1,2,3[4,5,6]]
lt2 = copy.copy(lt) # lt2 = lt.copy()

# 当lt2为lt的浅拷贝对象时,lt内部可变数据类型变化,lt2也随之变化;lt内部不可变化数据类型变化,lt2不变

Deep copy

import copy
lt = [1,2,3,[4,5,6]]
lt2 = copy.deepcopy(lt)

# 当lt2为lt的深拷贝对象时,lt内部任意数据类型的对象变化,lt2都不变化

Exception Handling

try:
    1/0
except Exception as e:
    print(e)
finally:
    print(1)
    
# assert
assert 1 == 1 # 满足条件跳过这一行 ; 不满足报错

# raise
raise 错误类型()  # 抛出异常

Data type classification

Variable or immutable

Variable: List / dictionary / collection

Immutable: integer / floating point / string / tuple

Ordered or unordered

Ordered: string / list / tuple

Disorder: dictionary / collection

Or a plurality of values

Ordered: Integer / Float / String

Disorder: a list / tuple / dictionary / collection

The basic file operations

Open the process file

# 1.打开文件
f = open(file_path,'r')
# 2.读写操作
f.read() / f.write()
# 3.关闭文件
f.close()

First, the character encoding

1.1 Basic Computer

  1. cpu: controlling the operation of the program (text editor removed from the memory data is read into memory)
  2. Memory: Run program (cpu after the operation, the memory containing the data summary text editor)
  3. Hard: storing data (text editor)

1.2 Text Editor

Computer known only 0 and 1

The role of the text editor: read and write data, save data

1.3 python interpreter

Function has a text editor

010100101010101 -> a = 1 # 5 very ordinary character, is not running when the python interpreter provided # character encoding

Define the variable will open up the memory space to store variables, memory that is known only 0 and 1, a = 1 -> 010101010010101 take some 0 and 1 # python3 he provided a string, when the python interpreter to run and difference python2 character encoding

1.4 Character Encoding

A process of mutual conversion between binary and character you can know: the character encoding

Early American use ascii code

Then the Chinese invented gbk coding

And then the shift coding artificial Japan

There have been a variety of coding the world

unicode: understanding language nations, nations coding

unicode: the eight English became English 16, takes up more memory space

1.5 What happens garbled

Encoding format is not uniform

文本编辑器支持的是utf8 ,你输入的是gbk --> 文件的存储

文件存储用了utf8 , 但是下次打开用了gbk --> 文件的读取

1.6 乱码的两种情况

中文的文本编辑器只认识中文,然后你输入了日本 --> 乱码 # encode 编程

文本编程器存储了中文(文件),但是你用了日本的编辑器打开这个文件--> 乱码 # decode 解码

1.7 解码乱码

什么格式存储,就什么格式读取,就不会乱码

windows电脑的记事本默认为gbk编码,除此之外其他的软件默认编码为utf8

二、python2和python3字符编码的区别

2.1 python解释器运行代码的流程

​ 1.启动python解释器(相当于文本编辑器)

​ 2.打开文件,显示这个字符并检查语法(涉及字符编码,a = 1 只是一个很普通的字符)

​ 3.解释字符(涉及字符编码,再去内存空间,生成一个a = 1的变量)

python2用的是ascii , python3默认是utf8读取字符

# coding:gbk 会告诉python3 解释器用gbk编码读取字符

python3(了解)

你看到的其实是unicode

但是终端帮你把这个unicode的0和1做一个转换,从unicode 转换成了终端能够识别的编码格式,然后变成中文

# coding:gbk
a = '中文'
print (a)

假设终端的默认编码是gbk,认识unicode编码的变量

假设终端的默认编码是utf8,认识unicode编码的变量

python2(了解)

unicode + 指定的coding 编码(str类型)

# coding:gbk
a = '中文'        # 用gbk编码存储了这堆0和1
b = u'中文'       # 用unicode编码存储了这堆0和1
print(a)         

终端是一个文本编辑器,会有默认编码

假设终端的默认编码是gbk,认识gbk编码的变量

假设终端的默认编码是utf8,不认识gbk编码的变量

三、文件的三种打开模式

文件的操作模式有三种(默认的操作模式为r模式):

  • r 模式为read
  • w 模式为write
  • a 模式为append

文件读写内容的格式有两种(默认的读写内容的模式为b模式):

  • t模式为text
  • b模式为bytes

需要注意的是:t、b这两种模式均不能单独使用,都需要与r/w/a之一连用

3.1 文件打开模式之r模式

​ r:read ,只读模式,只能读不能写,文件不存在时报错。

f = open('32.txt', mode='r')  # 报错
f.write()
f.close()

​ f.read() 读取文件指针会跑到文件的末端,如果再一次读取,读取的将是空格。

​ 由于f.read()一次性读取文件的所有内容,如果文件非常大的话,可能会造成内存爆掉,即电脑卡死。因此可以使用f.readline()/f.readlines()读取文件内容。

# f.readline()/f.readlines()
f = open('32.txt', mode='rt', encoding='utf8')
print(f"f.readable(): {f.readable()}")  # 判断文件是否可读
data1 = f.readline()
data2 = f.readlines()
print(f"data1: {data1}")
print(f"data2: {data2}")
f.close()

3.2 文件打开模式之w模式

w: 只能写,不能读,文件存在的时候就会清空文件后再写入内容;文件不存在的时候会创建文件后写入内容。

# wt
f = open('34w.txt', mode='wt', encoding='utf8')
print(f"f.readable(): {f.readable()}")
f.write('nick 真帅呀\n')  # '\n'是换行符
f.write('nick,nick, you drop, I drop.')
f.write('nick 帅的我五体投地')
f.flush()  # 立刻将文件内容从内存刷到硬盘
f.close()

3.3 文件打开模式之a模式

a : 可以追加。文件存在,则在文件的末端写入内容;文件不存在的时候会创建文件后内容。

# at
f = open('34a.txt', mode='at', encoding='utf8')
print(f"f.readable(): {f.readable()}")
f.write('nick 真帅呀\n')  # '\n'是换行符
f.write('nick,nick, you drop, I drop.')
f.write('nick 帅的我五体投地')
f.close()

3.4 文件打开读取二进制

b 模式是通用的模式,因为所有的文件在硬盘中都是以二进制的形式存储的,需要注意的是:b模式读写文件,一定不能加上encoding参数,因为二进制无法再编码。

try:
    import requests

    response = requests.get(
        'http://www.chenyoude.com/Python从入门到放弃/文件的三种打开模式-mv.jpg?x-oss-process=style/watermark')
    data = response.content

    f = open('mv.jpg?x-oss-process=style/watermark', 'wb')
    f.write(data)
    print('done...')
    f.close()
except Exception as e:
    print(e, '报错了,那就算了吧,以后爬虫处会详细介绍')

四、with管理文件操作上下文

之前我们使用open() 方法操作文件,但是open打开文件后我们需要手动释放文件对操作系统的占用。但是其实我们

可以更方便的打开文件,即python提供的上下文管理工具---with open()

with open('32.txt', 'rt', encoding='utf8') as f:
    print(f.read())

with open() 方法不仅提供自动释放操作系统占用的方法,并且with open 可以使用逗号分隔,一次性打开多个文件,实现文件的快速拷贝。

with open('32.txt','rb') as fr,\
    open('35.txt','rwb') as fw:
    f.write(f.read())

课后练习

https://www.cnblogs.com/foreversun92/p/11317149.html

今日小结

​ 今天主要讲了计算机基础知识的字符编码这一块的知识,以及python2和python3字符编码的区别。当然这些概念性的东西仅做了解就可以了,只需要记住什么格式存储,就什么格式读取,就不会乱码这个点就可以了。之后又讲了文件的三种打开方式,已经with open的使用方法。python对文件这块的操作,具体没有太多的内容,大致就是这些,熟练掌握,可以灵活运用就可以了。

Guess you like

Origin www.cnblogs.com/foreversun92/p/11318446.html