2025年4月15日 星期二 乙巳(蛇)年 正月十六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

【六行代码】Python逐行读取txt、换行输出到txt

时间:03-13来源:作者:点击数:35

先看效果

思路:将python逐行读取存入列表,然后换行输出

逐行读取效果 从input.txt到命令行输出列表

换行输出效果 从列表输出到ouput.txt

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

示例数据

  • contentType.put(".load" , "text/html");
  • contentType.put(".123" , "application/vnd.lotus-1-2-3");
  • contentType.put(".3ds" , "image/x-3ds");
  • contentType.put(".3g2" , "video/3gpp");
  • contentType.put(".3ga" , "video/3gpp");
  • contentType.put(".3gp" , "video/3gpp");
  • contentType.put(".3gpp" , "video/3gpp");
  • contentType.put(".602" , "application/x-t602");
  • contentType.put(".669" , "audio/x-mod");
  • contentType.put(".7z" , "application/x-7z-compressed");
  • contentType.put(".a" , "application/x-archive");
  • contentType.put(".aac" , "audio/mp4");

六行代码

  • #逐行读取
  • f=open('input.txt', encoding='gbk')
  • list=[]
  • [list.append(line.strip()) for line in f]
  • # print(list)
  • # line.strip() 去除首尾空格
  • #换行输出
  • with open('ouput.txt','w') as f:
  • [f.write(str(content)+'\n') for content in list]
  • f.close
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门