·Reading data from file
oFormat:
with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents)
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
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love python.")
NOTE: python can only writing string into text file. If you want to writing number into text file, please use str() .
· Exception
o ZeroDivisionError
try: print(5/0)except ZeroDivisionError: print("You can't divide by zero!")
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:
except ZeroDivisionError: pass
· You can also use try-except-else, if it is not error, it can figure out the answer. For example,
print("Give me two numbers, and I'll divide them.")print("Enter 'q' to quit.")while True: first = input("\nFirst Number: ") if first =='q': break second = input("Second number: ") try: answer = int(first)/int(second) except ZeroDivisionError: print("You can't divide by 0!") else: print(answer)
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:
with open(filename, encoding='UTF-8') as something:#REMEMBER IT!
· How to figure out the word number in one file?
Using the method split().For example,
words = contents.split()
· HOW TO USE JSON?
o json.dump() to storage data(存储数据)
o json.load() to read data
For example,
import jsonnumbers = [2,3,4,5,6,7,8,9,10,11,12,13]filename = 'numbers.json'with open(filename, 'w') as f_obj: json.dump(numbers, f_obj)with open(filename, 'r') as f_ob: numbs = json.load(f_ob)print(numbs)
Reconsitution in the book.