🌴 2022.06.08 下午 实验

实验六 文件访问

题目一

编写一个程序,通过键盘将曹操的《观沧海》写入文本文件gch.txt中

问题分析

将观沧海保存在listStr列表中,通过with open…as…写模式,file.write()方法逐行将列表中的数据存入txt文件中

代码

listStr = [
"观沧海",
"曹操",
"东临碣石,以观沧海。",
"水何澹澹,山岛竦峙。",
"树木丛生,百草丰茂。",
"秋风萧瑟,洪波涌起。",
"日月之行,若出其中。",
"星汉灿烂,若出其里。",
"幸甚至哉,歌以咏志。"]
with open("gch.txt", "w") as file:
for k in listStr:
file.write(k+"\n")

结果

Python实验17

题目二

创建一个名为grade.csv的文件,通过input()函数向文件中写入学生相关信息,格式为“姓名,性别,年龄,语文成绩,数学成绩,英语成绩”,当输入“-1”时结束输入。统计所有学生的总成绩、排序,并写入新文件statistics.csv

问题分析

在函数Input()中定义变量,headers[]保存表头信息,list1[]保存学生信息,将信息写入grade.csv文件,之后在Cout()函数中利用sorted()方法对总成绩排序,然后写入statisticx.csv文件

代码

"""
@Author:张时贰
@Date:2022年06月08日
@CSDN:张时贰
@Blog:zhsher.cn
"""
import csv


# 通过input()函数向文件中写入学生相关信息,格式为“姓名,性别,年龄,语文成绩,数学成绩,英语成绩”,当输入“-1”时结束输入
def Input():
headers = [ 'Name', 'Sex', 'Age', 'chNum', 'maNum', 'egNum' ]
list1 = [ ('李四', '男', 21, 80, 80, 80), ('王五', '男', 22, 95, 95, 95), ('张时叁', '女', 22, 85, 85, 85) ]

tu = ()
n = None
while (n != '-1'):
t1 = str ( input ( "输入名字:" ) )
t2 = str ( input ( "输入性别:" ) )
t3 = int ( input ( "输入年龄:" ) )
t4 = float ( input ( "输入语文分数:" ) )
t5 = float ( input ( "输入数学分数:" ) )
t6 = float ( input ( "输入英语分数:" ) )
tu = (t1, t2, t3, t4, t5, t6)
list1.append ( tu )
n = input ( '任意键回车继续,输入 -1 开始写入:' )

try:
with open ( "grade.csv", "w", encoding='ANSI', newline='' ) as file:
fw = csv.writer ( file )
fw.writerow ( headers )
fw.writerows ( list1 )
print ( "将文件写入grade.csv成功" )
except Exception as ex:
print ( ex )
print ( "将文件写入grade.csv失败" )


# 统计所有学生的总成绩、排序,并写入新文件statistics.csv中
def Count():
ch = [ ]
ma = [ ]
chn = 0
man = 0
list1 = [ ]
try:
with open ( "grade.csv", "r", encoding='ANSI', newline='' ) as file:
fr = csv.reader ( file )
list1 = [ li for li in fr ]

print ( "读取文件grade.csv成功" )
except Exception as ex:
print ( ex )
print ( "读取grade.csv失败" )
try:
with open ( "statistics.csv", "w", encoding='ANSI', newline='' ) as file:
fw = csv.writer ( file )
list1[ 0 ].append ( '总成绩' )
fw.writerow ( list1[ 0 ] )
# 按总成绩从小到大排名
for x in range ( 1, len ( list1 ) ):
list1[ x ].append ( float ( list1[ x ][ 3 ] ) + float ( list1[ x ][ 4 ] ) + float ( list1[ x ][ 5 ] ) )
print ( list1[ x ] )
list1 = sorted ( list1[ 1: ], key=lambda x: float ( x[ 6 ] ) )

fw.writerows ( list1 )
print ( "写入statisticx.csv成功" )

except Exception as ex:
print ( ex )
print ( "写入statisticx.csv失败" )


Input ()
Count ()

结果

Python实验18

题目三

编写一个程序,分别将一个数字、字符串、列表、元组、字典和集合写入一个二进制文件BFVle.dat中,然后从二进制文件BFVle.dat中读出并显示

问题分析

定义数字、字符串、列表、元组、字典和集合变量,利用data[]集合将数据保存起来,通过pickle库中pickle.dump()方法写操作,pickle.load()方法读操作,读文件通过while循环,发生异常时直接抛出

代码

"""
@Author:张时贰
@Date:2022年06月08日
@CSDN:张时贰
@Blog:zhsher.cn
"""
import pickle

num = 1 # 数字
string1 = "zhangshier.vip" # 字符串
list1 = [ 1.25, 21.06, 0.3, 4.7, 58.1 ] # 列表
tuple1 = (1, 8, 27, 64, 125) # 元组
dict1 = dict ( name="Mary", height=165, weight=51 ) # 字典
set1 = {1, 4, 9, 16, 25} # 集合

data = [ string1, list1, tuple1, dict1, set1 ] # 数据

with open ( "pickle_file.dat", "wb" ) as pickle_file: # 打开的二进制文件
for i in data:
pickle.dump ( i, pickle_file ) # 向文件中写入序列化内容
print ( "写入数据成功!" )

with open ( "pickle_file.dat", "rb" ) as pickle_file:
# y = pickle.load ( pickle_file ) # 一次只读一行,利用while()读多行
# print ( y )
while 1:
try:
y = pickle.load ( pickle_file )
print ( y )
except EOFError:
break

结果

Python实验19