|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #-----打印文件前N行------#
- file_name = input('请输入要打开的文件:')
- f = open(file_name)
- N = int(input('请输入需要显示该文件前几行:'))
- list1 = []
- for each_line in f:
- line = each_line.split('\n',1)
- list1.append(line)
- list2 = list1[0:N]
- f1 = open('C:/Users/asus/Desktop/record1.txt', 'w')
- f1.writelines(list2)
- for each_line in f1:
- print(each_line)
-
复制代码
程序运行后报错说:- TypeError: write() argument must be str, not list
复制代码
但是在- 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('C:/Users/asus/Desktop/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('record.txt')
复制代码
这个程序里,writelines(boy)就可以, 但是boy不是也是一个列表吗?
求问各位大佬这是怎么回事? |
|