·Reading data from file


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





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

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




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.