day09 作业 2018-07-26

2018-07-26  本文已影响0人  LPP27149

文本文件读写

# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     work
   Description :
   Author :       LPP
   date:          2018/7/26
-------------------------------------------------
   Change Activity:
                   2018/7/26:
-------------------------------------------------
"""
__author__ = 'LPP'
if __name__ == '__main__':
    # 文本文件读写
    with open('./test.txt', 'w',encoding='utf-8') as f:
        f.write('滚滚长江东逝水')

    with open('./test.txt', 'r', encoding='utf-8') as f:
        content = f.read()
        # print(content)
test.txt

滚滚长江东逝水

二进制文件读写

  
    with open('./pkq.jpeg', 'rb') as f1:
        img = f1.read()

    with open('./new_img.jpg', 'wb') as f1:
        f1.write(img)


pkq.jpeg
new_img.jpg

json文件读写

name = input('姓名')
tel = input('电话')
student = {'name': name, 'tel': tel}
try:
    with open('./new.json') as f:
        pass
except FileNotFoundError:
    with open('./new.json', 'w', encoding='utf-8') as f:
        json.dump([], f)

with open('./new.json', 'r', encoding='utf-8') as f:
    all_student = json.load(f)
    all_student.append(student)
    print(all_student)

with open('./new.json', 'w', encoding='utf-8') as f:
    json.dump(all_student, f)

姓名灰太狼
电话234567
[{'name': '罗飘飘', 'tel': '123456789'}, {'name': '皮皮虾', 'tel': '12345678'}, {'name': '派大星', 'tel': '987654'}, {'name': '可达鸭', 'tel': '244346889'}, {'name': '皮卡丘', 'tel': '7347660'}, {'name': '喜羊羊', 'tel': '9687687'}, {'name': '黑猫警长', 'tel': '110'}, {'name': '灰太狼', 'tel': '234567'}]


new.json
上一篇 下一篇

猜你喜欢

热点阅读