python从入门到实践2

10.文件和异常

import codecs

def count_words(filename):
        try:
                with open(filename,encoding= 'utf8') as f_obj:
                        contents = f_obj.read()
        except FileNotFoundError:
                print("file not exist")
        else:
                words = contents.split()
                num_words = len(words)
                print("the file "+ filename + " has about " + str(num_words) + " words")

filenames = ['E:\\fa.log','E:\\goods.sql','E:\\qiang']

for fn in filenames:
        count_words(fn)

10.1.3 读取文件

with open(filename,encoding= 'utf8') as f_obj:
        contents = f_obj.read()
        line = f_obj.readline()

10.2 写入文件

with open(filename,'w',encoding= 'utf8') as f_obj:
    f_obj.write("aaaxxxx")

10.2.3 追加到文件

with open(filename,'a',encoding= 'utf8') as f_obj:
    f_obj.write('apend some')

10.3 异常

try
    answer = 5/0
except:
    print("can't /0")
else:
    print(answer)

10.4 存储数据

import simplejson as json

Python 字典类型转换为 JSON 对象

    import simplejson as json

    data = [1,2,3,4,5,{'name':'aaa'}]

    filename = 'data.json'
    with open(filename,'w') as f_obj:
            json.dump(data,f_obj)

    with open(filename) as f_obj:
            str = f_obj.read()
            print(str)

    data2 = []

    with open(filename) as f_obj:
            data2 = json.load(f_obj)
    print("data2",type(data2),data2)

11.测试代码

发表评论

电子邮件地址不会被公开。

9 + 2 =