首页 > 编程 > Python > 正文

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

2020-01-04 15:36:36
字体:
来源:转载
供稿:网友

业务需求

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

jb51.txt

1:www.vevb.com
2:www.vevb.com
3:www.vevb.com
4:www.vevb.com
5:www.vevb.com
6:www.vevb.com
7:www.vevb.com
8:www.vevb.com
9:www.vevb.com
10:www.vevb.com
11:www.vevb.com
12:www.vevb.com
13:www.vevb.com
14:www.vevb.com
15:www.vevb.com
16:www.vevb.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的内容

python,两行一组

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


注:相关教程知识阅读请移步到python教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表