|
发表于 2021-3-1 11:24:27
|
显示全部楼层
本帖最后由 jackz007 于 2021-3-1 11:49 编辑
这个代码不允许在文件中有空行存在。
试试这个代码
- girl , boy , count = [] , [] , 1
- f = open('d:\\report.txt')
- report = list(f)
- f . close()
- if report[-1][:6] != '######': # 判断文件最后一行是不是由'######'构成的分隔行
- report . append('######') # 如果不是,那就添加一行,因为这个代码要遇到分隔行才会写文件
- for each_line in report:
- if each_line . strip(): # 过滤空文本行
- if each_line[:6] != '######': # 如果当前行是文本行
- if ':' in each_line: # 判断当前行是否可分割
- (person , spoken) = each_line . split(':' , 1) # 只对可分割行进行分割
- if person == '小甲鱼':
- boy . append(spoken)
- else:
- girl . append(spoken)
- else:
- print(each_line) # 把无法分割的行显示出来
- else:
- file_name_boy = 'boy_' + str(count) + '.txt' # 输出文件与源代码同目录
- file_name_girl = 'girl_' + str(count) + '.txt' # 输出文件与源代码同目录
- with open(file_name_boy , 'w') as boy_file:
- boy_file . writelines(boy)
- with open(file_name_girl , 'w') as girl_file:
- girl_file . writelines(girl)
- count += 1
- f . close()
复制代码 |
|