第2章Python文件操作与异常处理
习题答案
2-1.创建文件data.txt,共100000行,每行存放一个1~100之间的整数
importrandom
withopen(data.txt,w)asf:
for_inrange(100000):
f.write(str(random.randint(1,100))+\n)
2-2生成大文件ips.txt并统计频率
importrandom
importipaddress
withopen(ips.txt,w)asf:
for_inrange(1200):
net=ipaddress.ip_network(172.25.254.0/24)
ip=str(random.choice(list(net.hosts())))
f.write(ip+\n)
fromcollectionsimportCounter
withopen(ips.txt,r)asf:
ip_counts=Counter(f.read().splitlines())
forip,countinip_counts.most_common(10):
print(f{ip}:{count})
2-3定义函数func(filename)
deffunc(filename):
try:
withopen(filename,r)asf:
content=f.read()
returncontent#确保这个return在try块内部
exceptExceptionase:
print(fAnerroroccurred:{e})
returnNone#同样,这个return也在try块之外,但属于except块
#示例使用
content=func(data.txt)
ifcontent:
print(content[:100]+...)
else:
print(Nocontentorerror.)
2-4自定义异常类并捕获异常
classShortInputException(Exception):
def__init__(self,length,message=Inputtooshort):
self.length=length
self.message=f{message}.Theinputisoflength{self.length},expectingatleast5.
super().__init__(self.message)
try:
user_input=input(Enterastring:)
iflen(user_input)5:
raiseShortInputException(len(user_input))
else:
print(Success)
exceptShortInputExceptionase:
print(e)
exceptExceptionase:
print(fAnunexpectederroroccurred:{e})