本周将进行文件的学习

文件

编码

ASCII
Unicode
UTF-8(可变长度的Unicode)
GBK编码(汉字内码扩展规范)

编码:encode()
解码:decode()

文本

基于字符定长的ASCII
换行符:(\\n)

>>> print(\" hello \\nworld \\n \\ngoodbye 32 \\n\")
 hello 
world 
 
goodbye 32 

 # 两种不同的输入带来不同的输出
>>>> \"hello \\nworld \\n \\ngoodbye 32 \\n\"
\'hello \\nworld \\n \\ngoodbye 32 \\n\'
>>> 

二进制文件

照片音乐视频程序等
节省空间,精确,存取速度更快
变长的

文件的基本处理

读取,写入,定位
打开文件:open()
=open(,)
打开模式,如下格式:
\"在这里插入图片描述\"

#打开一个名为“music.mp3”的音频文件
>>> infile=open(\"music.mp3\",\"rb\")

字典

字典的添加

通过中括号 为字典增加一项

#在students中增加“204”对应Susan
>>> students={\"201\":\"John\",\"203\":\"Frank\"}   #字典用{}大括号表示
>>> students[\"204\"]=\"Susan\"       #添加的用[]表示
>>> students
{\'201\': \'John\', \'203\': \'Frank\', \'204\': \'Susan\'}
>>> 

删除字典中一项

>>> del students[\"204\"]
>>> students
{\'201\': \'John\', \'203\': \'Frank\'}
>>> 

字典的遍历

for key in dictionaryName:
print(key+\":\"+str(dictionaryName[name]))

>>> for key in students:
	print(key+\":\"+str(students[key]))

201:John
203:Frank
>>> 

其中key也可以换成值value,项item,以及key-value

判断 键 是否在字典中可以使用in 或 not in

>>> \"201\" in students
True
>>> \"202\" in students
False
>>> 

字典是无顺序的,即“201”与“202”谁先赋值,得到的字典都是相同的。

字典的方法

\"在这里插入图片描述\"

>>> students={\"201\":\"John\",\"202\":\"Peter\"}
>>> tuple(students.keys())
(\'201\', \'202\')
>>> tuple(students.values())
(\'John\', \'Peter\')
>>> tuple(students.items())
((\'201\', \'John\'), (\'202\', \'Peter\'))
>>> students.get(\"201\")
\'John\'
>>> students.pop(\"201\")
\'John\'
>>> students
{\'202\': \'Peter\'}
>>> students.clear()
>>> students
{}
>>> 
收藏 打印