1.题目:读取一个文件,显示除了以#号开头的行以外的所有行;
代码:
import os
f=open('1.txt', 'r')
content=f.readlines()
i=1
for temp in content:
if temp[0] != '#':
print("%d:%s"%(i,temp))
i+=1
运行截图:
2.题目:已知文本文件中存放了若干数字,请编写程序读取所有数字,排序以后进行输出;
代码:
f=open('2.txt','r')
content=f.readline()
content2=sorted(content,reverse=False)
print(content2)
运行截图:
3.题目:打开一个英文的文本文件,将该文件中的每个字母加密后写入到一个新文件,加密的方法是:将A变成B,B变成C,…Y变成Z,Z变成A;a变成b,b变成…z变成a ,其他字符不变化;
代码:
import os
f=open('3.1.txt','r+')
f1=open('3.2.txt','w+')
content=f.read()
for temp in content:
m=ord(temp)+1
if m >= 97 and m <= 123:
if m==123:
m=97
if m >= 65 and m <= 91:
if m == 91:
m=65
f1.write(chr(m))
f1.close()
f.close()
print("加密成功")
运行截图:
4.题目:打开一个英文文本文件,将其中大写字母变成小写,小写字母变成大写;
代码:
f=open('4.txt','r+')
content=f.readline()
f.write('\n')
for temp in content:
m = ord(temp)
if m >= 97 and m <= 123:
m -= 32
elif m >= 65 and m <= 91:
m += 32
f.write(chr(m))
f.close()
运行截图:
5.题目:录入一个学生的成绩,把该学生的成绩转换为A优秀、B良好、C合格、D不及格的形式,最好将该学生的成绩打印出来。要求用assert断言处理分数不合理的情况。
代码:
while(1):
score=int(input("请输入学生成绩:\n"))
if score<=100 and score>=90:
print("A优秀")
elif score<=89 and score>=80:
print("B良好")
elif score<=79 and score>=60:
print("C及格")
elif score<60 and score>=0:
print("D不及格")
else:
assert score>100 and score<0,"分数不合理!!!"
运行截图: