简明Python教程学习笔记8
12、输入输出
(1)简介
输入输出的方法:
- raw_input()和print
- 文件的读写
(2)文件
1 # coding=utf-8 2 poem = """\ 3 Programing is fun 4 When the work is done 5 if ou wanna make your work also fun: 6 use Python! 7 """ 8 9 f = file("poem.txt", "w") 10 f.write(poem) 11 f.close() 12 13 f = file("poem.txt") 14 while True: 15 line = f.readline() 16 if len(line) == 0: 17 break 18 print line, # 注意使用逗号,不会自动换行 19 f.close()
输出:
当前目录新增了文件poem.txt
(3)存储器pickle
cpickle比pickle快很多
dump写
load读
1 # -*- coding:utf-8 -*- 2 3 4 import cPickle as p 5 6 shoplistfile = "shoplist.data" 7 8 shoplist = ["apple", "mango", "carrot"] 9 10 # write to the file 11 f = file(shoplistfile, "w") 12 p.dump(shoplist, f) # dump the object to a file 13 f.close() 14 15 del shoplist # Remove the shoplist 16 17 # Read back from the storage 18 f = file(shoplistfile) 19 storedlist = p.load(f) # load the object from a file 20 f.close() 21 print storedlist
输出:
保存的文件,可读性不好