2017-10-18  963 views 1

Python chapter 10 learning notes

 标签:  

·Reading data from file

oFormat:

In line one, the function open(filename, 'x') is used to open a file, 'x' can be relpaced by 'w', 'r', 'a', 'r+'.

r只读r+读写,不创建

w新建只写w+新建读写,二者都会将文件内容清零

(以w方式打开,不能读出。w+可读写)

以a,a+的方式打开文件,附加方式打开

a附加写方式打开,不可读;a+: 附加读写方式打开)

以 'U' 标志打开文件, 所有的行分割符通过 Python 的输入方法(例#如 read*() ),返回时都会被替换为换行符\n. ('rU' 模式也支持 'rb' 选项) . 

r和U要求文件必须存在

不可读的打开方式w和a

若不存在会创建新文件的打开方式:a,a+,w,w+

The key word with…as… is an easy way to name something as xxx.

Using the method read() can read the data to contents.

Using the method readlines() can read the data frome file, and then put them into a list.

Using the method strip() can delete the left blank.

·        Writing data into file

NOTE: python can only writing string into text file. If you want to writing number into text  file, please use str() .

·        Exception

o   ZeroDivisionError

Using try-except is good way to tell user that you can't divide by zero. It is also can be used in other exceptions.

·        If you don't want to tell user anything, you can just do as followed:

·        You can also use try-except-else, if it is not error, it can figure out the answer. For example,

o   FileNotFoundError

Just like ZeroDivisionError

o   Analysis text file

If we meet this error:UnicodeDecodeError: 'gbk' codec can't decode byte 0x99 in position 1056: illegal multibyte sequence

We need to do this:

·        How to figure out the word number in one file?

Using the method split().For example,

·        HOW TO USE JSON?

o   json.dump() to storage data(存储数据)

o   json.load() to read data

For example,

Reconsitution in the book.

1 条留言  访客:0 条  博主:0 条   引用: 1 条

来自外部的引用: 1 条

  • Python语言程序设计(第7周)知识点整理 – 小奥の部落格

给我留言

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: