文件操作及异常处理

文件操作

'''
open() 打开文件
file:要操作的文件名,绝对路径(从根目录开始)/相对路径(./ ../)
mode:r只读(默认)/ w只写(没有就创建,且覆盖源文件)/ x(创建并写入)/ a追加
encoding:utf-8(一个汉字转成3个字节)/gbk(一个汉字转成2个字节)
返回值:文件对象,后续直接对文件对象进行操作

read()和readline()若读到文件末尾就返回空字符串
'''

# 分步骤操作(创建并写入内容)
#txtObj = open('test.txt', mode='x', encoding='utf-8')  # 新建文件并只写
#txtObj.write('今天天气真好')  # 覆盖式写入
#txtObj.close()  # 关闭文件,且自动保存

# 分步骤操作(读取所有内容)
#txtObj = open('test.txt', mode='r', encoding='utf-8')  # 只读
#print(txtObj.read())    # 返回读取的内容


# 组合操作(追加内容)
# 打开文件的另一种写法 with,不用写close(),缩进结束就关闭
#with open('test.txt', mode='a', encoding='utf-8') as txtObj:
    #txtObj.write('\n我想出去玩')


# 组合操作(读取所有内容)
#with open('test.txt', encoding='utf-8') as txtObj:
    #txt = txtObj.read()
    #print(txt)

# 组合操作(循环读取每一行内容)
#with open('test.txt', encoding='utf-8') as txtObj:
    #while True:
        #line = txtObj.readline()
        #if line:
            #print(line, end='')
        #else:
            #break
        
        
        

'''
json语法:
1、json 中的数据类型 -> Python中的数据类型
    对象{} -> 字典
    数组[] -> 列表
    字符串"" -> 字符串'' ""
    数字类型 -> int/float
    bool类型(true/false) -> True/False
    空值 null -> None
2、json文件,是一个对象或者数组,对象和数据可以相互嵌套
3、json中的对象,是由键值对组成,键必须是字符串类型
4、json中的数据直接使用逗号隔开

{
    "name": "小明",
    "age": 18,
    "isMan": true,
    "school": null,
    "hobby": ["听歌", "吃饭", "打豆豆"],
    "address": {"country": "中国", "city": "广州"}
}
'''

# Python操作json文件(字典对象)
#import json
#with open('jsonTxt_dict.json', encoding='utf-8') as f:
    #j = json.load(f)
    #for k, v in j.items():
        #print(k, v)

# Python操作json文件(列表对象:多个字典)
#import json
#with open('jsonTxt_list.json', encoding='utf-8') as f:
    #j = json.load(f)
    #for i in j:
        #s = "男" if i['isMan'] else "女"
        #print(f"姓名:{i['name']},年龄:{i['age']},性别:{s},城市:{i['address']['city']}")




# json文件写入(将Python中列表或字典转为json文件)
#import json
#l = [{'name': '陈', 'age': 18}, {'name': '李', 'age': 20}]
#d = {'name': '王', 'age': 17}
#with open('listWriteJson.json', mode='x', encoding='utf-8') as f:
    #json.dump(l, f, ensure_ascii=False)


#with open('dictWriteJson.json', mode='x', encoding='utf-8') as f1:
    #json.dump(d, f1, ensure_ascii=False, indent=4)

 

异常处理

'''
# 异常捕获的完整结构
try:
    执行可能会报错的代码
except 异常类型:
    发生了指定异常类型时执行的代码
except Exception as e:
    发生了其它异常类型时执行的代码
else:
    没有异常时执行的代码
finally:
    不管有没有发生异常都会执行的代码

'''
# 不区分异常类型
#try:
    #num = int(input('请输入一个整数:'))
    #print(num)
#except:
    #print('输入类型不对')


# 区分指定异常类型
#try:
    #num = int(input('请输入一个整数:'))
    #print(8 / num)
#except ZeroDivisionError:
    #print('输入的数字不能是0')
# except ValueError:
    #print('输入的数字不能是整数')

# 未知异常类型
#try:
    #num = int(input('请输入一个整数:'))
    #print(8 / num)
#except Exception as e:  # e表示捕获到的异常对象,是具体的异常原因
    #print(f'发生了异常,异常原因是:{e}')


# 捕获异常完整结构
#try:
    #num = int(input('请输入一个整数:'))
#except ValueError:
    #print('输入错误')
#else:
    #if num % 2 == 0:
        #print('输入的数字是一个偶数')
    #else:
        #print('输入的数字是一个奇数')
#finally:
    #print('程序运行结束')







'''
抛出异常
'''
def pwd_input():
    pwd = input('请输入密码:')
    if len(pwd) < 8:
        raise Exception('密码长度不能低于8位')
    else:
        print(pwd)
        
pwd_input()

 

posted @ 2024-01-01 11:49  Sakura媛媛  阅读(4)  评论(0编辑  收藏  举报