gezikang 发表于 2020-6-8 11:41:22

小甲鱼老师 each_line 问题

看了小甲鱼老师文件那课,自己试了试,发现each_line没什么用,根据书本写了个程序如下图
def save_file(boy,girl,count):
    file_name_boy = 'boy_' + str(count) + '.txt'
    file_name_girl ='girl_' + str(count) + '.txt'

    boy_file = open(("D://KK_Movies//%s"%file_name_boy),'w')
    girl_file = open(("D://KK_Movies//%s"%file_name_girl),'w')

    boy_file.writelines(boy)
    girl_file.writelines(girl)

    boy_file.close()
    girl_file.close()

def split_file(file_name):
    count = 1
    boy = []
    girl = []

    f= open(file_name)

    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://KK_Movies//abc.txt")


最后

Traceback (most recent call last):
File "C:/Users/戈/Desktop/P8.py", line 38, in <module>
    split_file("D://KK_Movies//abc.txt")
File "C:/Users/戈/Desktop/P8.py", line 21, in split_file
    for each_line in f :
ValueError: I/O operation on closed file.
出现这两个 问题,有没有大佬看看

Twilight6 发表于 2020-6-8 11:43:44

把关闭文件移动到for 循环外 ,不然你循环关闭文件了...而只打开一次文件
f.close()

完整代码:
def save_file(boy,girl,count):
    file_name_boy = 'boy_' + str(count) + '.txt'
    file_name_girl ='girl_' + str(count) + '.txt'

    boy_file = open(("D://KK_Movies//%s"%file_name_boy),'w')
    girl_file = open(("D://KK_Movies//%s"%file_name_girl),'w')

    boy_file.writelines(boy)
    girl_file.writelines(girl)

    boy_file.close()
    girl_file.close()

def split_file(file_name):
    count = 1
    boy = []
    girl = []

    f= open(file_name)

    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://KK_Movies//abc.txt")

gezikang 发表于 2020-6-8 14:55:24

Twilight6 发表于 2020-6-8 11:43
把关闭文件移动到for 循环外 ,不然你循环关闭文件了...而只打开一次文件




谢谢大佬!!! 好了

Twilight6 发表于 2020-6-8 14:55:56

gezikang 发表于 2020-6-8 14:55
谢谢大佬!!! 好了

~~~ 记得设置最佳哈~
页: [1]
查看完整版本: 小甲鱼老师 each_line 问题