1.请在test.txt文件中写入"wow,so beautiful!",并关闭文件
def main():
try:
file = open(“d:\test.txt”,“w”)
file.write(“wow,so beautiful!”)
finally:
file.close()
if name == “main”:
main()
2.创建文件data.txt,写入共100行数据,每行存放一个1~100之间的整数
import random
def main():
with open(file = “d:\data.txt”,mode = “w”) as file:
for dig in range(100):
content = ("{}\n".format(random.randint(1,100)))
file.write(content)
if name == “main”:
main()
3.京东二面笔试题:生成一个大文件ips.txt,要求写入120行,每行随机为172.25.254.0/254段的ip;
import random
def main():
with open(file = “d:\ips.txt”,mode = “w”) as file:
for dig in range(120):
content = ("{}\n".format(random.randint(0,254)))
file.write(“172.25.254.”+content)
if name == “main”:
main()
ps:本次实验是在实验室做的,就没有截图了,是在pycharm上运行的。
4:例题:编写Phthon代码,利用异常处理方式,模拟现场最终成绩的计算过程,评审要求 : 评委人数大于3人,每个评委评分满分100分,结果去掉一个最高分,去掉一个最低分后求平均。
while True:
try:
n = int(input(“请输入评委总人数:”))
if n <= 3:
print(“评委人数太少,必须多于3人。”)
else:
break
except ValueError:
print(“请输入正确的评委人数:”)
scores = []
for i in range(n):
while True:
try:
score = eval(input(“请输入第{0}个评委的分数:”.format(i+1)))
assert 0<=score<=100 #判断输入的成绩是否有效
scores.append(score)
break
except:
print(“请输入100以内的数字”)
finalscore = round((sum(scores)-max(scores)-min(scores))/(len(scores)-2),2)
print(“最终成绩为:{}”.format(finalscore))