python将文本分每两行一组并保存到文件

秋天来啦!秋天来啦!田野里就是美丽的图画。花生躲在地下,包着红色的毛毯,住在土黄色的房间里睡大觉。玉米姐姐穿着绿色的裙子,在叶子上跳舞,南瓜爷爷鼓着金黄色的大肚子,坐着高级的南瓜车,一边看风景一边享受。西红柿露出火红火红的脸蛋,正对着我们微笑。谁使秋天这样美?看,田野里的菊花做出了回答,菊花顶着一个爆炸头,在微风中轻轻摇动,好像在说:是勤劳的人们画出了秋天的图画。

业务需求

需要将文本文件分每两行一组

jb51.txt

1:www.haodaima.com
2:www.haodaima.com
3:www.haodaima.com
4:www.haodaima.com
5:www.haodaima.com
6:www.haodaima.com
7:www.haodaima.com
8:www.haodaima.com
9:www.haodaima.com
10:www.haodaima.com
11:www.haodaima.com
12:www.haodaima.com
13:www.haodaima.com
14:www.haodaima.com
15:www.haodaima.com
16:www.haodaima.com

核心代码:

# -*- coding: utf-8 -*-
'''
python读取文件,每两行为一组
'''
def fenhang(infile,outfile):

 infopen = open(infile,'r',encoding='utf-8')
 outopen = open(outfile,'w',encoding='utf-8')
 lines = infopen.readlines()
 i = 1
 for line in lines:
  if i % 2 == 0:
   outopen.write(line+'\n')
  else:
   outopen.write(line)
  i += 1
 infopen.close()
 outopen.close()
fenhang("jb51.txt","o.txt")

通过执行 python jb51.txt

o.txt的内容

到这里这篇文章就完成了,希望大家以后多多支持。

标签: 两行 并保存