Python 学习笔记【文件对象】


读写文件

>>> file = open("test.txt","w")
>>> file.write("hello test file\n")
>>> file.close()


>>> file = open("test.txt")
>>> file.readline()
'hello test file\n'


在文件中存储解析python对象 >>> x,y,z = 1,2,3
>>> s = 'kuma'
>>> d = {'a':4,'b':5}
>>> l = [6,7,8]
>>> file = open('datafile.txt','w')
>>> file.write(s+'\n')
>>> file.write('%s,%s,%s\n' % (x,y,z))
>>> file.write(str(l) + '$' + str(d) + '\n')
>>> file.close()
>>> 
>>> bytes = open('datafile.txt').read()
>>> bytes
"kuma\n1,2,3\n[6, 7, 8]${'a': 4, 'b': 5}\n"
>>> print bytes
kuma
1,2,3
[6, 7, 8]${'a': 4, 'b': 5}

eval函数,功能与javascript中的eval类似 >>> file = open('datafile.txt','r')
>>> line = file.readline()
>>> line
'kuma\n'
>>> line = file.readline()
>>> line
'1,2,3\n'
>>> line = file.readline()
>>> line
"[6, 7, 8]${'a': 4, 'b': 5}\n"
>>> parts = line.split('$')
>>> parts
['[6, 7, 8]', "{'a': 4, 'b': 5}\n"]
>>> objects = [eval(p) for p in parts]
>>> objects
[[6, 7, 8], {'a': 4, 'b': 5}]

不过和javascript中的eval一样,由于可以执行任何代码,所以eval并不安全,一般使用pickle库代替eval来存储python的原生对象 >>> file = open('datafile.txt','w')
>>> pickle.dump(d,file)
>>> file.close()
>>> file = open('datafile.txt')
>>> e = pickle.load(file)
>>> e
{'a': 4, 'b': 5}

相关内容