python中,我们使用open来打开一个文件
1:open一次读取一数据行,通过迭代器来读取所有内容
2:readline(),是从打开的文件中读取一行
3:seek(),让我们从头开始读取文件
4:close(),关闭一个文件
一个完整openfile的例子,涉及是处理数据,转换为json,然后存储,然后读取出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#!/usr/bin/env python # coding=utf-8 import json names = [] scores = [] try: data = open('test.txt') for each_line in data: try: (name,score) = each_line.split(":") print "%s got : %s " % (name,score) names.append(name) scores.append(score) except ValueError: pass data.close() except IOError: print "The data file is missiing" try: names_txt = open('names_txt','w') scores_txt = open('scores_txt','w') names_txt.write(json.dumps(names)) scores_txt.write(json.dumps(scores)) names_txt.close() scores_txt.close() except IOError: print 'file error' try: data_new = open('names_txt') content = json.load(data_new) print 'the data from the txt: %s' % content print content[0] except: print 'error' pass |
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021