标题:python 例
只看楼主
madfrogme
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:21
帖 子:1160
专家分:1106
注 册:2009-6-24
得分:0 
文件的操作,创建一个file类的实例,使用readline方法读文件的每一行
程序代码:
#!/usr/bin/python
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!
'''

f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

f = file('poem.txt')
# 如果不指定模式,默认为读模式
while True:
    line = f.readline()
    if len(line) == 0: # 表明到了EOF
        break
    print line,
    # 逗号是为了避免python 自动添加新行
f.close()

$ ./t.py
        Programming is fun
        When the work is donw
        If you wanna make your work also fun:
        use Python!


The quieter you become, the more you can hear
2012-09-05 20:14
madfrogme
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:21
帖 子:1160
专家分:1106
注 册:2009-6-24
得分:0 
Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,比pickle快1000倍.  import..as语法。这是一种便利方法,以便于我们可以使用更短的模块名称
程序代码:
#!/usr/bin/python

import cPickle as p

shoplistfile = "shoplist.data"

shoplist = ['apple', 'mango', 'carrot']

f = file(shoplistfile, 'w')

p.dump(shoplist, f)     #dump the object to a file

f.close()

del shoplist    # remove the shoplist 

f = file(shoplistfile)

storedlist = p.load(f) # readback from the storage

print storedlist


$ ./t.py
['apple', 'mango', 'carrot']

The quieter you become, the more you can hear
2012-09-06 22:41



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-380375-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.416102 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved