Python-100-Days-Day11

11837 단어 언어 학습
오늘은 문서 읽기와 쓰기에 관한 부분입니다.
import time

#                       
def r1():
    f = None
    try:
        f = open('   .txt', 'r', encoding='utf-8')
        print(f.read())
    except FileNotFoundError:
        print('         !')
    except LookupError:
        print('        !')
    except UnicodeDecodeError:
        print('         !')
    finally:
        if f:
            f.close()
def r2():
    #            
    with open('   .txt', 'r', encoding='utf-8') as f:
        print(f.read())

    #   for-in      
    with open('   .txt', mode='r') as f:
        for line in f:
            print(line, end='')
            time.sleep(0.5)
    print()

    #             
    with open('   .txt') as f:
        lines = f.readlines()
    print(lines)

import json


# jason
def r3():
    mydict = {
        'name': '  ',
        'age': 38,
        'qq': 957658,
        'friends': ['   ', '   '],
        'cars': [
            {'brand': 'BYD', 'max_speed': 180},
            {'brand': 'Audi', 'max_speed': 280},
            {'brand': 'Benz', 'max_speed': 320}
        ]
    }
    try:
        with open('data.json', 'w', encoding='utf-8') as fs:
            json.dump(mydict, fs)
    except IOError as e:
        print(e)
    print('      !')

#      ,    
def r4():
    try:
        with open('guido.jpg', 'rb') as fs1:
            data = fs1.read()
            print(type(data))  # 
        with open('  .jpg', 'wb') as fs2:
            fs2.write(data)
    except FileNotFoundError as e:
        print('         .')
    except IOError as e:
        print('         .')
    print('      .')

좋은 웹페이지 즐겨찾기