29讲课堂问题
def save_file(boy,girl,count):file_name_boy = "boy_" + str(count) + ".txt"
file_name_girl = "girl_" + str(count) + ".txt"
boy_file = open(file_name_boy,"w")
girl_file = open(file_name_girl,"w")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
def split_file(file_name):
f = open("D:/record.txt")
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != "======":
(role,line_spoken) = each_line.split(':',1)
if role == "小甲鱼":
boy.append(line_spoken)
if role == "小客服":
girl.append(line_spoken)
else:
save_file(boy,girl,count)
boy = []
girl = []
count += 1
save_file(boy,girl,count)
f.close()
split_file("D:/record.txt")
问题:
1.为什么我运行没有新增文件
2.split_file("D:/record.txt")为什么传入实参没有被调用
1.为什么我运行没有新增文件
认真检查下,可能在其他文件夹里,正常情况,生成的新文件在你当前脚本的目录下
我这里测试代码成功运行了哈~也成功生成了文本文件
2.split_file("D:/record.txt")为什么传入实参没有被调用
因为你 f = open("D:/record.txt") 直接填入的是路径了,改成 f = open(file_name) 即可
参考代码:
def save_file(boy, girl, count):
file_name_boy = "boy_" + str(count) + ".txt"
file_name_girl = "girl_" + str(count) + ".txt"
boy_file = open(file_name_boy, "w")
girl_file = open(file_name_girl, "w")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
def split_file(file_name):
f = open(file_name)
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != "======":
(role, line_spoken) = each_line.split(':', 1)
if role == "小甲鱼":
boy.append(line_spoken)
if role == "小客服":
girl.append(line_spoken)
else:
save_file(boy, girl, count)
boy = []
girl = []
count += 1
save_file(boy, girl, count)
f.close()
split_file("D:/record.txt")
Twilight6 发表于 2020-8-9 15:53
认真检查下,可能在其他文件夹里,正常情况,生成的新文件在你当前脚本的目录下
我这里测试代码 ...
谢谢大佬,我把脚本位置放错地方了,然后试了一下你的f = open(file_name)也是OK 的
页:
[1]