|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
作业题,这样写就会报错ValueError: I/O operation on closed file,如果把函数全部撤掉,语句带入就不会报错。
为什么捏?
代码如下:
带函数,会报错:
- count=0
- number=['1','2','3']
- def open_new_files(count):
- file_name_boy =str('boy_'+ number[count] +'.txt')
- file_name_girl =str('girl_'+ number[count] + '.txt')
- boy_file = open(file_name_boy,'w')
- girl_file=open(file_name_girl,'w')
- open_new_files(count)
- f_read = open('record.txt','r')
- for each_line in f_read:
- if each_line[2] == '鱼':
- boy_file.write(each_line.split(':')[1])
- boy_file.write('\n')
- if each_line[2] == '服':
- girl_file.write(each_line.split(':')[1]) #为这里会报错:ValueError: I/O operation on closed file.
- girl_file.write('\n')
- if each_line[2]=='=':
- boy_file.close()
- girl_file.close()
- count+=1
- open_new_files(count)
- open_new_files(count)
- f_read.close()
复制代码
不带函数,冗长,但是不报错:
- count=0
- number=['1','2','3','4,','5','6','7','8','9','0']
- def open_new_files(count):
- file_name_boy =str('boy_'+ number[count] +'.txt')
- file_name_girl =str('girl_'+ number[count] + '.txt')
- boy_file = open(file_name_boy,'w')
- girl_file=open(file_name_girl,'w')
- file_name_boy =str( 'boy_'+ number[count] +'.txt')
- file_name_girl =str('girl_' + number[count] + '.txt')
- boy_file = open(file_name_boy,'w')
- girl_file = open(file_name_girl,'w')
- f_read = open('record.txt','r')
- for each_line in f_read:
- if each_line[2] == '鱼':
- boy_file.write(each_line.split(':')[1])
- boy_file.write('\n')
- if each_line[2] == '服':
- girl_file.write(each_line.split(':')[1])
- girl_file.write('\n')
- if each_line[2]=='=':
- boy_file.close()
- girl_file.close()
- count+=1
- file_name_boy =str('boy_'+ number[count] +'.txt')
- file_name_girl =str('girl_'+ number[count] + '.txt')
- boy_file = open(file_name_boy,'w')
- girl_file=open(file_name_girl,'w')
- boy_file.close()
- girl_file.close()
- f_read.close()
复制代码 |
|