python异常处理的语法格式_python学习之文件操作及异常处理

在python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件。

open(文件名,访问模式) e.g. f = open('test.txt', 'w')

如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

要读取二进制文件,比如图片、视频等等,用'rb', 'wb', 'ab'等模式打开文件即可

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

seek(offset, from)有2个参数: offset:偏移量 from:方向

0:表示文件开头;

1:表示当前位置;

2:表示文件末尾

1). 把位置设置为:从文件开头,偏移5个字节

2). 把位置设置为:文件最开始

3). 把位置设置为:文件最末尾

01_open函数读取文件操作.py

#打开文件/etc/passwd, 默认的打开模式是'r'

f = open('/etc/passwd')

print(f.read())

#io.UnsupportedOperation: not writable

#f.write('hello')

02_open以写的方式打开文件.py

"""

##mode=r, 文件不存在,直接报错; 只能read

##FileNotFoundError: [Errno 2] No such file or directory: 'doc/hello.txt'

#f = open('doc/hello.txt')

#print(f.read())

##mode=w, 1). 文件不存在,会自动创建文件; 2). 只能write 3). 自动清空文件内容

#f = open('doc/hello.txt', mode='w')

##print("读取文件中...", f.read())

##f.write('hello python\n')

##print("写入成功......")

"""

mode=a+,

1). 文件不存在,会自动创建文件;

2). r w

3). 文件追加并不会清空文件

"""

f = open('doc/world.txt', 'a+')

#移动指针到文件最开始

f.seek(0, 0)

print(f.read())

#f.write('hello python\n')

print(f.closed)

print(f.mode)

print(f.name)

f.close()

print("关闭文件后.....")

print(f.closed)

print(f.mode)

print(f.name)

03_cp命令的实现.py

import os

os.path.exists('/etc/passwd')

Out[3]: True

os.path.exists('/etc/passwd1')

Out[4]: False

"""

import os

src_filename = input("要拷贝的文件: ")

#1). 判断文件是否存在

if os.path.exists(src_filename):

dst_filename = input("目标文件: ")

#2). mode='r'打开文件读取文件内容

#注意: 要读取二进制文件,比如图片、视频等等,用'rb', 'wb', 'ab'等模式打开文件即可.

src_f = open(src_filename, 'rb')

content = src_f.read()

#3). mode='r'打开文件写入要拷贝的文件内容

dst_f = open(dst_filename, 'wb')

dst_f.write(content)

#4). 关闭文件对象

src_f.close()

dst_f.close()

print('拷贝成功')

else:

print("要拷贝的文件%s不存在" %(src_filename))

04_文件读写操作.py

from collections.abc import Iterable

f = open('/etc/passwd', 'r')

#当文件比较小时, 使用read、readlines方法读取.

print(f.read())

print(''50)

#当文件比较大时, 使用readline方法读取.

#将指针移动到文件最开始, 然后指针向右移动5个字节。

f.seek(5, 0)

print(f.readline())

print(f.readline())

print(''50)

#将指针移动到文件最开始,

f.seek(0, 0)

print(f.readlines())

#名词: 可迭代对象: 可以通过for循环遍历的对象

#print("文件对象时可迭代对象吗? ", isinstance(f, Iterable))

for index, line in enumerate(f):

print("第%s行" %(index+1), line)

"""

from collections.abc import Iterable

#需求: 将/etc/passwd文件后5行写入doc/world.txt文件

f1 = open('/etc/passwd')

tail_five_line = f1.readlines()[-5:]

#print(tail_five_line)

#print(len(tail_five_line))

f2 = open('doc/world.txt', 'w')

f2.writelines(tail_five_line)

print("write ok")

"""

总结:方法一: 调用close()方法关闭文件。文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,

并且操作系统同一时间能打开的文件数量也是有限的:

方法二: Python引入了with语句来自动帮我们调用close()方法:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

05_with语句工作原理.py

with语句工作原理:

python中的with语句使用于对资源进行访问的场合,

保证不管处理过程中是否发生错误或者异常都会自动

执行规定的(“清理”)操作,释放被访问的资源,

比如有文件读写后自动关闭、线程中锁的自动获取和释放等。

"""

#enter, exit

#f = open('xxxx')

with open('/etc/passwd') as f:

print('in with:', f.closed) # False

print(f.readlines()[-1])

print('out with:', f.closed) # True"""

os,语义为操作系统,处理操作系统相关的功能,可跨平台。 比如显示当前目录下所

有文件/删除某个文件/获取文件大小......

• os模块中的rename()可以完成对文件的重命名操作。

rename(需要修改的文件名, 新的文件名)

• os模块中的remove()可以完成对文件的删除操作

remove(待删除的文件名)

06_os模块系统信息获取.py

import os

#1). 返回操作系统类型, 值为posix,是Linux操作系统, 值为nt, 是windows操作系统

print(os.name)

os_name = 'Linux' if os.name =='posix' else 'Windows'

print("当前操作系统: %s" %(os_name))

#2). 操作系统的详细信息

detail_info = os.uname()

print(detail_info)

print("主机名:", detail_info.nodename)

print("硬件架构:", detail_info.machine)

print("系统名称:", detail_info.sysname)

print("Linux内核的版本号:", detail_info.release)

#3). 系统环境变量等价于Linux的env命令

print(os.environ)

#4). 通过key值获取环境变量对应的value值

print(os.environ['PATH'])

"""

07_os模块文件和目录的操作.py

import os

from os.path import isabs, abspath, join

#1. 判断是否为绝对路径---'/tmp/hello', 'hello.png', 'qq/hello.mp3'

print(isabs('/tmp/hello'))

print(isabs('hello.py'))

#2. 生成绝对路径

#filename = 'hello.py'

filename = '/tmp/hello.py'

if not isabs(filename):

print(abspath(filename))

#3. 'hello.png'

#返回一个绝对路径: 当前目录的绝对路径+ 文件名/目录名

#'/tmp/hello' , 'python.txt' ==== /tmp/hello/python.txt

#C:\tmp\hello\python.txt

print(join('/tmp/hello', 'python.txt'))

#4.获取目录名或者文件名

#5. 创建目录/删除目录

#6. 创建文件/删除文件

#7. 文件重命名(mv)

#8. 判断文件或者目录是否存在

#9. 分离后缀名和文件名

#10. 将目录名和文件名分离"""

07_目录常见应用.py

"""

import os

BASE_DIR = os.path.abspath(os.path.dirname(file))

print(file) # /home/kiosk/201911python/day07_code/07_目录常见应用.py

print(os.path.dirname(file))

print(os.path.abspath(os.path.dirname(file)))"""

08_验证码生成器.py

def draw_code_image(str_code='A34G'):

#引入绘图模块, Image表示画布对象; ImageDraw表示画笔对象; ImageFont表示字体对象;

from PIL import Image, ImageDraw, ImageFont

#定义变量,用于画面的背景色、宽、高

#RGB:(255,0,0), (0, 255,0), (0, 0, 255)

bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)

width = 100

height = 25

#创建画布对象

im = Image.new('RGB', (width, height), bgcolor)

#创建画笔对象

draw = ImageDraw.Draw(im)

#调用画笔的point()函数绘制噪点

for i in range(100):

xy = (random.randrange(0, width), random.randrange(0, height))

fill = (random.randrange(0, 255), 255, random.randrange(0, 255))

draw.point(xy, fill=fill)

#构造字体对象

font = ImageFont.truetype('/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc',

23)

#构造字体颜色

fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))

for index, item in enumerate(str_code):

#print(5 +index20)) # (5,2) (25, 2), (45,2)

draw.text((5 + (index 20), 2), item, font=font, fill=fontcolor)

return im

"""

import random

def generate_str_code(length=4):

"""随机生成验证码"""

import string

strings = string.ascii_letters + string.digits

return "".join(random.sample(strings, length))

def draw_code_image(str_code):

"""根据给丁的字符串验证码绘制验证码图片"""

#引入绘图模块, Image表示画布对象; ImageDraw表示画笔对象; ImageFont表示字体对象;

from PIL import Image, ImageDraw, ImageFont

#定义变量,用于画面的背景色、宽、高

#RGB:(255,0,0), (0, 255,0), (0, 0, 255)

width = 100

height = 25

white_color = (255, 255, 255)

black_color = (0, 0, 0, 0)

green_color = (0, 255, 0)

#创建画布对象

im = Image.new('RGB', (width, height), white_color)

#创建画笔对象

draw = ImageDraw.Draw(im)

#调用画笔的point()函数绘制噪点

for i in range(100):

xy = (random.randrange(0, width), random.randrange(0, height))

draw.point(xy, fill=green_color)

#构造字体对象 shell命令: fc-list :lang=zh

font = ImageFont.truetype('doc/wqy-zenhei.ttc', 23)

for index, item in enumerate(str_code):

#print(5 +index20)) # (5,2) (25, 2), (45,2)

draw.text((5 + (index 20), 2), item, font=font, fill=black_color)

return im

if name == 'main':

str_code = generate_str_code()

#返回的图片对象

im = draw_code_image(str_code)

im.save('hello.png')"""

08_验证码生成器.py

Author: lvah

Date: 2019-12-15

Connect: 976131979@qq.com

Description:

项目需求: 批量验证码图片生成器

1). 可生成数字、大写、小写字母及三者混合类型的验证码

2). 支持自定义验证码字符数量

3). 支持自动调整验证码图片的大小

4). 支持自定义干扰点的数量

5). 支持自定义验证码图文颜色

"""

import os

import random

white_color = (255, 255, 255)

black_color = (0, 0, 0, 0)

green_color = (0, 255, 0)

def generate_str_code(length=4):

"""随机生成验证码"""

import string

strings = string.ascii_letters + string.digits

return "".join(random.sample(strings, length))

def draw_code_image(str_code, item_width=25, height=25, point_count=100,

bg_color=black_color, font_color=white_color):

"""

根据给定的字符串验证码绘制验证码图片

:param str_code:

:param item_width:

:param height:

:param point_count:

:param bg_color:

:param font_color:

:return:

"""

#引入绘图模块, Image表示画布对象; ImageDraw表示画笔对象; ImageFont表示字体对象;

from PIL import Image, ImageDraw, ImageFont

#定义变量,用于画面的背景色、宽、高

#RGB:(255,0,0), (0, 255,0), (0, 0, 255)

#根据验证码的长度自动调整画布的宽度

width = len(str_code) item_width

#创建画布对象

im = Image.new('RGB', (width, height), bg_color)

#创建画笔对象

draw = ImageDraw.Draw(im)

#调用画笔的point()函数绘制噪点

for i in range(point_count):

xy = (random.randrange(0, width), random.randrange(0, height))

draw.point(xy, fill=green_color)

#构造字体对象 shell命令: fc-list :lang=zh

font = ImageFont.truetype('doc/wqy-zenhei.ttc', 23)

for index, item in enumerate(str_code):

#print(5 +index25)) # (5,2) (25, 2), (45,2)

draw.text((5 + (index * 25), 0), item, font=font, fill=font_color)

return im

if name == 'main':

from tqdm import tqdm

verifyCodeCount = 100

dirname = 'vCode'

for count in tqdm(range(verifyCodeCount)):

#He3x ===== He3x.png

str_code = generate_str_code(length=10)

#返回的图片对象

im = draw_code_image(str_code)

#生成图片文件的绝对路径

filename = os.path.join(dirname, str_code + random.choice(['.png', '.jpg']))

im.save(filename)

print("生成图片验证码成功")

"""

json模块详解:

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

python 中str类型到JSON中转为unicode类型,None转为null,dict对应object;

pyhton中的集合不能转成json格式

• ensure_ascii=False: 中文存储需要设定

• indent=4: 增加缩进,增强可读性,但缩进空格会使数据变大

• separators=(',',':'): 自定义分隔符,元素间分隔符为逗号, 字典key和value值的分隔符为冒号

• sort_keys=True: 字典排序

10_存储json数据.py

"""

import json

info = dict(user1='00000', user2='11111', 粉条='1111')

#编码: 字典转成json数据格式

json_info = json.dumps(info)

print(info, json_info)

print(type(info), type(json_info))

#编码: 字典转成json并存储未文件

json.dump(info, open('doc/info.json', 'w'), indent=4, ensure_ascii=False)

print("写入json文件成功")

"""

11_加载json文件.py

"""

import json

filename = 'doc/info.json'

#解码: 将文件中的json数据转换成python对象及型处理

python_info = json.load(open(filename))

print(python_info)

print(python_info.get('粉条'))

"""

我们碰到集合对象, datetime对象,或者自定义的类对象等json默认不支持的数据类型时,我们就需

要自定义编解码函数。有两种方法来实现自定义编解码。

12_json模块自定义编码与解码.py

"""

from datetime import datetime

from datetime import date

import json

def time2str(dateObj):

return str(dateObj)

dt = datetime.now()

today = date.today()

#自定义编码和解码

with open('doc/date.json', 'w') as f:

#Object of type date is not JSON serializable

json.dump(today, f, default=time2str)

print('dump ok')"""

python的pickle模块实现了python的所有数据序列和反序列化。与JSON不同的是pickle不是用于多种

语言间的数据传输,它仅作为python对象的持久化或者python程序间进行互相传输对象的方法,因此

它支持了python所有的数据类型。cPickle是pickle模块的C语言编译版本相对速度更快。

总结:

1、JSON只能处理基本数据类型。pickle能处理所有Python的数据类型。

2、JSON用于各种语言之间的字符转换。pickle用于Python程序对象的持久化或者Python程序间对象

网络传输,但不同版本的Python序列化可能还有差异。

13_pickle数据的序列化.py

import pickle

#编码

from datetime import date

today = date.today()

with open('date.pkl', 'wb') as f:

pickle.dump(today, f)

print('pickle dump ok')

#解码: 反序列化

with open('date.pkl', 'rb') as f:

today = pickle.load(f)

print('pickle load ok')

print(today)

"""

15_忽略注释行.py

"""

filename = 'doc/passwd.bak'

with open(filename) as f:

for line in f:

if not line.startswith('#'):

print(line)"""

异常处理机制

Python 的异常机制主要依赖 try 、except 、else、finally 和 raise 五个关键字。

• try 关键字后缩进的代码块简称 try 块,它里面放置的是可能引发异常的代码;

• except 关键字对应异常类型和处理该异常的代码块;

• 多个 except 块之后可以放一个 else 块,表明程序不出现异常时还要执行 else 块;

• finally 块用于回收在 try 块里打开的物理资源,异常机制会保证 finally 块总被执行;

• raise 用于引发一个实际的异常,raise 可以单独作为语句使用,引发一个具体的异常对象;

除了处理实际的错误条件之外,对于异常还有许多其它的用处。在标准 Python 库中

一个普通的用法就是试着导入一个模块,然后检查是否它能使用。导入一个并不存在的

模块将引发一个 ImportError 异常。

你可以使用这种方法来定义多级别的功能――依靠在运行时哪个模块是有效的,或支

触发异常

持多种平台 (即平台特定代码被分离到不同的模块中)。

Python 允许程序自行引发异常,自行引发异常使用 raise 语句来完成。

raise语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,

args 是自已提供的异常参数。

raise [Exception [, args [, traceback]]]

自定义异常

用户自定义异常都应该继承 Exception 基类或 Exception 的子类,在自定义异常类时基

本不需要书写更多的代码,只要指定自定义异常类的父类即可

• 不要过度使用异常

• 不要使用过于庞大的 try 块

• 不要忽略捕获到的异常

16_异常处理机制.py

import os

dirname = 'dir'

filename = os.path.join(dirname, 'hello.html') # dir/hello.html

#try 关键字后缩进的代码块简称 try 块,它里面放置的是可能引发异常的代码;

try:

with open(filename, 'w') as f:

f.write('hello')

#except 关键字对应异常类型和处理该异常的代码块;

except FileNotFoundError as e:

os.mkdir(dirname)

#如何没有产生任何异常时, 执行的内容

else:

print('no exception')

#finally 块用于回收在 try 块里打开的物理资源,异常机制会保证 finally 块总被执行

finally:

print("不管是否有异常都要执行的代码")

"""

17_异常处理范例.py

"""

try:

print(10/0) # ZeroDivisionError, 异常处理之后, try里面的代码并不会继续执行。

print(a) # NameError

except ZeroDivisionError as e:

print('zero')

except NameError as e:

print('name')

else:

print('ok')

print('step 1')"""

18_抛出异常.py

#IndexError

#NameError

class AgeError(ValueError):

pass

age = 1000

if 0 < age < 150:

print('age legal')

else:

raise AgeError('age error')

作业:

1 批量改名:

import os

path = 'doc/'

for i in os.listdir(path):

new_name = '[西部开源]-' + i

os.rename(os.path.join(path,i),os.path.join(path,new_name))

print(new_name)

2 忽略注释行:

filename = 'doc/passwd.bak'

with open(filename) as f:

for line in f:

if not line.startswith("#"):

print(line)

3 密码簿:

import os

f = open('doc/book.txt','a+')

def main():

print("密码簿管理系统")

print("1.增加网址和密码")

print("2.删除网址和密码")

print("3.修改网址和密码")

print("4.查询网址和密码")

print("5.退出系统")

def add_book():

f = open("doc/book.txt",'a+')

web = input("输入网址:")

passwd = input("输入密码:")

f.write("网址名:"+web+"\t"+"密码:"+passwd+"\n")

print("写入成功")

f.close()

def del_book():

f = open("doc/book.txt", 'a+')

web = input("输入要删除的网址:")

f.seek(0,0) # 重新设置位置到文件开头

a = f.readlines()

temp_file = open("doc/tmp.txt",'w')

i = 0

for temp in a:

b = temp.split("\t")

net_name = b[0].split(":")

if web == net_name[1]:

print("删除成功!")

i = 1

continue

else:

temp_file.write(temp)

if i == 0:

print("没有找到要删除的网址!!")

temp_file.close()

f.close()

os.remove("doc/book.txt")

os.rename("doc/tmp.txt", "doc/book.txt")

def change_book():

f = open("doc/book.txt", "a+")

f.seek(0, 0) # 重新设置位置到文件开头

re_net = input("请输入要修改的网址名:")

a = f.readlines()

temp_file = open("doc/tmp.txt", "w+")

i = 0

for temp in a:

b = temp.split("\t")

net_name = b[0].split(":")

if re_net == net_name[1]:

print("要修改的网址已找到!!")

web = input("请输入新的网址名")

passwd = input("请输入新的密码")

temp_file.write("网址名:" + web + "\t" + "密码:" + passwd + "\n")

print("修改成功!!")

i = 1

continue

else:

temp_file.write(temp)

if i == 0:

print("没有找到要修改的网址!!")

temp_file.close()

f.close()

os.remove("doc/book.txt")

os.rename("doc/tmp.txt", "doc/book.txt")

def find_book():

f = open("doc/book.txt")

f.seek(0, 0) # 重新设置位置到文件开头

goal = input("请输入要查询的网址名:")

content = f.readlines()

i = 0

length = len(content)

for temp in content:

i += 1

b = temp.split("\t")

net_name = b[0].split(":")

if goal == net_name[1]:

print(temp, end="")

i = 1

elif i == length and goal != net_name:

print("没有找到。。")

break

f.close()

main()

while True:

num = input("请输入序号:\n")

num = int(num)

if num == 1:

add_book()

elif num == 2:

del_book()

elif num == 3:

change_book()

elif num == 4:

find_book()

elif num == 5:

f.close()

exit()

else:

print("请输入正确序号")

continue

main()

学生管理系统(文件版)

import re # 导入正则表达式模块

import os # 导入操作系统模块

filename = "students.txt" # 定义保存学生信息的文件名

def menu():

# 输出菜单

print('''

学生信息管理系统

=============== 功能菜单 ===============

│ 1 录入学生信息 │

│ 2 查找学生信息 │

│ 3 删除学生信息 │

│ 4 修改学生信息 │

│ 5 排序 │

│ 6 统计学生总人数 │

│ 7 显示所有学生信息 │

│ 0 退出系统

''')

def main():

ctrl = True # 标记是否退出系统

while (ctrl):

menu() # 显示菜单

option = input("请选择:") # 选择菜单项

option_str = re.sub("\D", "", option) # 提取数字

if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:

option_int = int(option_str)

if option_int == 0: # 退出系统

print('您已退出学生成绩管理系统!')

ctrl = False

elif option_int == 1: # 录入学生成绩信息

insert()

elif option_int == 2: # 查找学生成绩信息

search()

elif option_int == 3: # 删除学生成绩信息

delete()

elif option_int == 4: # 修改学生成绩信息

modify()

elif option_int == 5: # 排序

sort()

elif option_int == 6: # 统计学生总数

total()

elif option_int == 7: # 显示所有学生信息

show()

'''1 录入学生信息'''

def insert():

stdentList = [] # 保存学生信息的列表

mark = True # 是否继续添加

while mark:

id = input("请输入ID(如 1001):")

if not id: # ID为空,跳出循环

break

name = input("请输入名字:")

if not name: # 名字为空,跳出循环

break

try:

english = int(input("请输入英语成绩:"))

python = int(input("请输入Python成绩:"))

c = int(input("请输入C语言成绩:"))

except:

print("输入无效,不是整型数值....重新录入信息")

continue

stdent = {"id": id, "name": name, "english": english, "python": python, "c": c} # 将输入的学生信息保存到字典

stdentList.append(stdent) # 将学生字典添加到列表中

inputMark = input("是否继续添加?(y/n):")

if inputMark == "y": # 继续添加

mark = True

else: # 不继续添加

mark = False

save(stdentList) # 将学生信息保存到文件

print("学生信息录入完毕!!!")

#将学生信息保存到文件

def save(student):

try:

students_txt = open(filename, "a") # 以追加模式打开

except Exception as e:

students_txt = open(filename, "w") # 文件不存在,创建文件并打开

for info in student:

students_txt.write(str(info) + "\n") # 按行存储,添加换行符

students_txt.close() # 关闭文件

'''2 查找学生成绩信息'''

def search():

mark = True

student_query = [] # 保存查询结果的学生列表

while mark:

id = ""

name = ""

if os.path.exists(filename): # 判断文件是否存在

mode = input("按ID查输入1;按姓名查输入2:")

if mode == "1":

id = input("请输入学生ID:")

elif mode == "2":

name = input("请输入学生姓名:")

else:

print("您的输入有误,请重新输入!")

search() # 重新查询

with open(filename, 'r') as file: # 打开文件

student = file.readlines() # 读取全部内容

for list in student:

d = dict(eval(list)) # 字符串转字典

if id is not "": # 判断是否按ID查

if d['id'] == id:

student_query.append(d) # 将找到的学生信息保存到列表中

elif name is not "": # 判断是否按姓名查

if d['name'] == name:

student_query.append(d) # 将找到的学生信息保存到列表中

show_student(student_query) # 显示查询结果

student_query.clear() # 清空列表

inputMark = input("是否继续查询?(y/n):")

if inputMark == "y":

mark = True

else:

mark = False

else:

print("暂未保存数据信息...")

return

'''3 删除学生成绩信息'''

def delete():

mark = True # 标记是否循环

while mark:

studentId = input("请输入要删除的学生ID:")

if studentId is not "": # 判断要删除的学生是否存在

if os.path.exists(filename): # 判断文件是否存在

with open(filename, 'r') as rfile: # 打开文件

student_old = rfile.readlines() # 读取全部内容

else:

student_old = []

ifdel = False # 标记是否删除

if student_old: # 如果存在学生信息

with open(filename, 'w') as wfile: # 以写方式打开文件

d = {} # 定义空字典

for list in student_old:

d = dict(eval(list)) # 字符串转字典

if d['id'] != studentId:

wfile.write(str(d) + "\n") # 将一条学生信息写入文件

else:

ifdel = True # 标记已经删除

if ifdel:

print("ID为 %s 的学生信息已经被删除..." % studentId)

else:

print("没有找到ID为 %s 的学生信息..." % studentId)

else: # 不存在学生信息

print("无学生信息...")

break # 退出循环

show() # 显示全部学生信息

inputMark = input("是否继续删除?(y/n):")

if inputMark == "y":

mark = True # 继续删除

else:

mark = False # 退出删除学生信息功能

'''4 修改学生成绩信息'''

def modify():

show() # 显示全部学生信息

if os.path.exists(filename): # 判断文件是否存在

with open(filename, 'r') as rfile: # 打开文件

student_old = rfile.readlines() # 读取全部内容

else:

return

studentid = input("请输入要修改的学生ID:")

with open(filename, "w") as wfile: # 以写模式打开文件

for student in student_old:

d = dict(eval(student)) # 字符串转字典

if d["id"] == studentid: # 是否为要修改的学生

print("找到了这名学生,可以修改他的信息!")

while True: # 输入要修改的信息

try:

d["name"] = input("请输入姓名:")

d["english"] = int(input("请输入英语成绩:"))

d["python"] = int(input("请输入Python成绩:"))

d["c"] = int(input("请输入C语言成绩:"))

except:

print("您的输入有误,请重新输入。")

else:

break # 跳出循环

student = str(d) # 将字典转换为字符串

wfile.write(student + "\n") # 将修改的信息写入到文件

print("修改成功!")

else:

wfile.write(student) # 将未修改的信息写入到文件

mark = input("是否继续修改其他学生信息?(y/n):")

if mark == "y":

modify() # 重新执行修改操作

'''5 排序'''

def sort():

show() # 显示全部学生信息

if os.path.exists(filename): # 判断文件是否存在

with open(filename, 'r') as file: # 打开文件

student_old = file.readlines() # 读取全部内容

student_new = []

for list in student_old:

d = dict(eval(list)) # 字符串转字典

student_new.append(d) # 将转换后的字典添加到列表中

else:

return

ascORdesc = input("请选择(0升序;1降序):")

if ascORdesc == "0": # 按升序排序

ascORdescBool = False # 标记变量,为False表示升序排序

elif ascORdesc == "1": # 按降序排序

ascORdescBool = True # 标记变量,为True表示降序排序

else:

print("您的输入有误,请重新输入!")

sort()

mode = input("请选择排序方式(1按英语成绩排序;2按Python成绩排序;3按C语言成绩排序;0按总成绩排序):")

if mode == "1": # 按英语成绩排序

student_new.sort(key=lambda x: x["english"], reverse=ascORdescBool)

elif mode == "2": # 按Python成绩排序

student_new.sort(key=lambda x: x["python"], reverse=ascORdescBool)

elif mode == "3": # 按C语言成绩排序

student_new.sort(key=lambda x: x["c"], reverse=ascORdescBool)

elif mode == "0": # 按总成绩排序

student_new.sort(key=lambda x: x["english"] + x["python"] + x["c"], reverse=ascORdescBool)

else:

print("您的输入有误,请重新输入!")

sort()

show_student(student_new) # 显示排序结果

''' 6 统计学生总数'''

def total():

if os.path.exists(filename): # 判断文件是否存在

with open(filename, 'r') as rfile: # 打开文件

student_old = rfile.readlines() # 读取全部内容

if student_old:

print("一共有 %d 名学生!" % len(student_old))

else:

print("还没有录入学生信息!")

else:

print("暂未保存数据信息...")

''' 7 显示所有学生信息 '''

def show():

student_new = []

if os.path.exists(filename): # 判断文件是否存在

with open(filename, 'r') as rfile: # 打开文件

student_old = rfile.readlines() # 读取全部内容

for list in student_old:

student_new.append(eval(list)) # 将找到的学生信息保存到列表中

if student_new:

show_student(student_new)

else:

print("暂未保存数据信息...")

#将保存在列表中的学生信息显示出来

def show_student(studentList):

from prettytable import PrettyTable

if not studentList:

print("(o@.@o) 无数据信息 (o@.@o) \n")

return

field_names = ("ID", "名字", "英语成绩", "Python成绩", "C语言成绩", "总成绩")

table = PrettyTable(field_names=field_names)

for info in studentList:

sum_score = info.get('english', 0) + info.get('python', 0) + info.get('c', 0)

row = list(info.values())

row.append(sum_score)

table.add_row(row)

print(table)

if __name__ == "__main__":

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值