python 两行一组 python将文本分每两行一组并保存到文件
为援不可图 人气:0想了解python将文本分每两行一组并保存到文件的相关内容吗,为援不可图在本文为您仔细讲解python 两行一组的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,两行一组,下面大家一起来学习吧。
业务需求
需要将文本文件分每两行一组
jb51.txt
1:www.qb5200.com
2:www.qb5200.com
3:www.qb5200.com
4:www.qb5200.com
5:www.qb5200.com
6:www.qb5200.com
7:www.qb5200.com
8:www.qb5200.com
9:www.qb5200.com
10:www.qb5200.com
11:www.qb5200.com
12:www.qb5200.com
13:www.qb5200.com
14:www.qb5200.com
15:www.qb5200.com
16:www.qb5200.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的内容
到这里这篇文章就完成了,希望大家以后多多支持。
加载全部内容