源代码下载:下载地址在这里
# 029
aFile = file(r'C:\in.txt', 'r')
while True:
line = aFile.readline()
if len(line) == 0:
break
# end of if
print line,
# end of while
aFile.close()
output:
>>>
This is the first line.
This is the second line.
This is the third line.
>>> ......
源代码下载:下载地址在这里
e.g.1
# 030
aFile = file(r'C:\temp.txt', 'a')
aFile.write('又添加了一行。')
aFile.close()
output:
e.g.2
# 030
aFile = file(r'C:\temp.txt', 'a')
aFile.write('又添加了一行。')
aFile.close()
output:
e.g.3
实现根据原始文件有没有最后一行空行的情况来进行“完美添加”。
# 031
aFile = file(r'C:\temp.txt', 'r')
lastLine = ''
while True:
line = aFile.readline()
if len(line) == 0:
break
# end of if
lastLine = line
# end of while
aFile.close()
aFile = file(r'C:\temp.txt', 'a')
if not lastLine.endswith('\n'): # 说明源文件没有一个空行,需要重新另起一行
aFile.write('\n')
# end of if
aFile.write('这是新添加的一行!')
aFile.close()
此时无论原始文件是e.g.1的样子还是e.g.2的样子,结果都是:
......
源代码下载:下载地址在这里
# 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()
del aList # 现在已经没有aList所指的对象了,甚至没有aList这个引用了
f = file(objectFileName, 'r')
storedObject = p.load(f)
print storedObject
output:
>>>
[1, 2, 3]
>>>
当然,在文件中,Python采用了一种便于自己分辨对象类型的格式来存储:
......
源代码下载:下载地址在这里
# 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! ......
源代码下载:下载地址在这里
# 034
class Person:
def __init__(self, name):
self.name = name # 这一句中第一个name是类中包含的域,第二个name是传进来的参数
# end of def
def sayHello(self):
print 'Hello!'
# end of def
# end of class
p = Person('Ning')
print p.name
p.sayHello()
output:
Ning
Hello! ......
源代码下载:下载地址在这里
# 035
class Person:
population = 0 #这个变量是属于整个类的
def __init__(self, name):
self.name = name
print '初始化 %s' % self.name
Person.population += 1
# end of def
def __del__(self):
print '%s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print '我是最后一个人了!'
else:
print '还有%d个人。' % Person.population
# end of if
# end of def
def sayHi(self):
print 'Hi, my name is %s' % self.name
# end of def
def howMany(self):
print Person.population
# end of def
# enf of class
ning = Person('Ning')
ning.sayHi()
ning.howMany()
#zhang = Person('Zhang')
#zhang.sayHi()
#zhang.howMany()
#ning.sayHi()
#ning.howMany()
output:
注意!下面是两次运行的结果,可以看出del(析构函数)的运行时间是不确定的。这个现象的原因在于Python的垃圾回收机制的自动回收时间是不确定的。
初始 ......