Python入门的36个例子 之 36
# 040
import time
try:
f = file('040_Finally.py')
while True:
line = f.readline()
if len(line) == 0:
break
time.sleep(0.33)
print line,
# end of while
finally:
f.close()
print 'Closed the file.'
# end of try
output:
>>>
# 040
import time
try:
f = file('040_Finally.py')
while True:
line = f.readline()
if len(line) == 0:
break
time.sleep(0.33)
print line,
# end of while
finally:
f.close()
print 'Closed the file.'
# end of try
Closed the file.
>>>
源代码下载:下载地址在这里
相关文档:
例1:
# _018
# This is a module (if write Chinese in a module, there will be a error)
def func1():
print 'This is function 1.'
def func2():
print 'This is function 2.'
def func3():
print 'This is function 3.'
# 019
# 使用“import”语句调用模块:
import _018_Module
_ ......
源代码下载:下载地址在这里
# 022
listNum1 = [1, 3]
listNum2 = [2, 4]
listStr1 = ['a', 'c']
listStr2 = ['b', 'd']
# 列表的合并
list1 = listNum1 + listStr1
for ele in list1:
print ele
print '\n'
# 判断列表中是否包含某元素
print 'b' in list1
print 1 in list1
# 删除某个元素
for ele in ......
源代码下载:下载地址在这里
# 032
# 其实cPickle这个模块起到的作用可以用“完美地协调了文件中的内容(对象)和代码中的引用”来形容
import cPickle as p # 这条语句给cPickle起了个小名p
objectFileName = r'C:\Data.txt'
aList = [1, 2, 3]
f = file(objectFileName, 'w')
p.dump(aList, f)
f.close ......
源代码下载:下载地址在这里
# 033
class Person:
age = 22
def sayHello(self): # 方法与函数的区别在于需要一个self参数
print 'Hello!'
# end of def
# end of class # 这是我良好的编程风格
p = Person()
print p.age
p.sayHello()
output:
22
Hello! ......