del 语句删除一个变量。 执行del x会删除该对象的最后一个引用,也就是该对象的引用计数会减少为0,这会导致该对象从此“无法访问”或“无法抵达”。从此刻起,该对象就成为垃圾回收机制的回收对象。任何追踪或调试程序会给一个对象增加一个额外的引用,这会推迟该对象被回收的时间。
3.5.5 垃圾回收
虽然解释器跟踪对象的引用计数,但垃圾收集器负责释放内存。垃圾收集器是一块独立的代码,它用来寻找引用计数为0的对象。它也负责检查那些虽然引用计数大于0但也应该被销毁的对象。Python的垃圾收集器实际上是一个引用计数和一个循环垃圾收集器。
3.6 第一个Python程序
创建文件并写入内容
#!/user/bin/env python
'makeTextFile.py -- Create text file'
import os
ls = os.linesep
# get file name
fname = raw_input("FileName:")
while True:
if os.path.exists(fname):
print "Error '%s' already exists" % fname
fname = raw_input("FileName:")
else:
break
# get file content (text) lines
all = []
print "\n Enter lines ('.' by itself to quit). \n"
# loop until user terminates input
while True:
entry = raw_input('> ')
if entry == '.':
break
else:
all.append(entry)
# write lines to file with proper line-ending
fproj = open(fname, 'w')
fproj.writelines(['%s%s' % (x,ls) for x in all])
fproj.close()
print 'Done!'
os.path.exists() 判断文件是否存在
os.lineseq 行结束符,跨平台,Unix下代表'\n', win32下代表'\r\n'。
文件对象的writelines()方法接收包含行结束符的结果列表。
['%s%s' % (x,ls) for x in all] 列表解析,使用一个for循环将所有结果输入到一个列表中。
文件读取和显示
#!/user/bin/env python
'readTextFile.py -- read and display text file'
# get filename
fname = raw_input('Enter filename: ')
print
try:
fobj = open(fname, 'r')
except IOError, e:
print "*** file open error:", e
else:
# display contents to the screen
for eachLine in fobj:
print eachLine,
fobj.close()