小甲鱼课后作业疑问
f = open('dh.txt')boy = []
girl = []
count = 1
for each_line in f:
if each_line[:2] != '==':
(role,say) = each_line.split(':',1)
if role == '小甲鱼':
boy.append(say)
if role == '小客服':
girl.append(say)
else:
boysay = 'boy'+str(count) + '.txt'
girlsay = 'girl' +str(count) + '.txt'
boyopen = open(boysay,'w')
girlopen = open(girlsay,'w')
boyopen.writelines(boy) #为什么不能用write而要用writelines?
girlopen.writelines(girl)
boy= []
girl = []
count += 1
boyopen.close()
girlopen.close()
boysay = 'boy'+str(count) + '.txt'
girlsay = 'girl' +str(count) + '.txt'
boyopen = open(boysay,'w')
girlopen = open(girlsay,'w')
boyopen.writelines(boy)
girlopen.writelines(girl)
boy= []
girl = []
count += 1
boyopen.close()
girlopen.close()
f.close()
问题见代码注释
boyopen.write() 和 boyopen.writelnes有什么区别?
不都是写入吗? file.write(str) : 将字符串写入文件,返回的是写入的字符长度。
file.writelines(sequence) : 向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。
https://www.runoob.com/python3/python3-file-methods.html boyopen . writelines(boy) 用于将多个字符串写入文件。其中,输入参数 boy 必须是一个可迭代对象,在本例中,它是一个由多个字符串构成的列表,而 boyopen . write(s) 用于将单个字符串写入文件。输入参数 s 是一个普通的字符串。
页:
[1]