任务描述
本题的前一小题教学链接:Python高级应用之文件的读取、文件夹的创建和删除
本关任务:创建词人文件夹,并将该词人所写的词文件保存至该词人的文件夹中。
宋词.txt文件结构如下
预输出的文件夹样式如下
文本文件保存内容如下
参考答案
import os
import shutil
if os.path.exists("wjcl/src/step5/cr"):
shutil.rmtree("wjcl/src/step5/cr")
os.mkdir("wjcl/src/step5/cr")
f1=open("wjcl/src/step1/宋词.txt",'r')
# 代码开始
s=[]
temp ={}
key = None
forline in f1:
lines = line.strip().split()
if len(lines)== 2:
s.append(temp.copy())
temp.clear()
key = line
temp[key]= [line]
else:
temp[key].append(line)
for item in s[1:]:
for k,v in item.items():
lines = k.strip().split()
if not os.path.exists("wjcl/src/step5/cr/" + lines[-1]):
os.mkdir("wjcl/src/step5/cr/"+ lines[-1])
with open(f"wjcl/src/step5/cr/{lines[-1]}/{lines[0]}.txt","w") as f:
f.write("".join(v))
# 代码结束