python分批定量读取文件内容,输出到不同文件中的方法

作者:yiranxijie 时间:2021-10-05 21:29:30 

一、文件内容的分发

应用场景:分批读取共有358086行内容的txt文件,每取1000条输出到一个文件当中


# coding=utf-8
# 分批读取共有358086行内容的txt文件,每取1000条输出到一个文件当中

txt_path = "E:/torrenthandle.txt"
base_path="E:/torrent_distribution/"

def distribution( ):
f = open(txt_path,"r")
lines = f.readlines()
f2=open(base_path+"1.txt","w")
content=""
for i in range( 1,len(lines) ):
 if ( i%1000!=0 ):
  content+=lines[i-1]
 else:
  content+=lines[i-1]
  f2.write(content.strip('\n'))
  block_path=base_path+str(i)+".txt"
  f2=open(block_path,"w")
  content=""
#最后的扫尾工作
content+=lines[i]
f2.write(content.strip('\n'))
f2.close()
f.close()

distribution( )

二、文件夹(目录)下的内容分发

应用场景:分批读取目录下的文件,每取1000条输出到一个新的目录当中


# coding: utf-8

import os
import shutil

sourcepath = "E:\\sample"
distribution_path = "E:\\sample\\distribution\\"

if __name__ =='__main__':
rs = unicode(sourcepath , "utf8")
count = 1
savepath = unicode(distribution_path+"1", "utf-8")
if not os.path.exists(savepath):
 os.makedirs(savepath)
for rt,dirs,files in os.walk(rs):
 for fname in files:
  if ( count%1000!=0 ):
   shutil.copy(rt + os.sep + fname,savepath)
   #os.remove(rt + os.sep + fname)
  else:
   shutil.copy(rt + os.sep + fname,savepath)
   #os.remove(rt + os.sep + fname)
   savepath = unicode(distribution_path+str(count), "utf-8")
   if not os.path.exists(savepath):
    os.makedirs(savepath)
  count+=1

来源:https://blog.csdn.net/u013863751/article/details/71719856

标签:python,读取,文件
0
投稿

猜你喜欢

  • Python分析微信好友性别比例和省份城市分布比例的方法示例【基于itchat模块】

    2022-01-04 08:14:09
  • python3获取两个日期之间所有日期,以及比较大小的实例

    2023-01-31 06:54:52
  • jquery validate.js表单验证的基本用法入门

    2023-07-02 05:30:47
  • python计算机视觉opencv卡号识别示例详解

    2023-04-14 13:58:25
  • 基于python实现把图片转换成素描

    2022-01-01 23:11:11
  • Golang源码分析之golang/sync之singleflight

    2024-04-25 15:07:26
  • Jupyter Notebook内使用argparse报错的解决方案

    2023-05-08 21:43:52
  • Python中不同进制互相转换(二进制、八进制、十进制和十六进制)

    2022-02-12 02:32:55
  • uni-app中弹窗的使用与自定义弹窗

    2024-05-10 14:15:24
  • Python同时向控制台和文件输出日志logging的方法

    2021-10-12 07:35:11
  • Python制作旋转花灯祝大家元宵节快乐(实例代码)

    2023-10-24 02:49:18
  • Go语言学习笔记之golang操作MongoDB数据库

    2024-01-27 05:06:23
  • Oracle 10g各个帐号的访问权限、登录路径、监控状态命令查询等等

    2024-01-24 22:46:05
  • python 函数的缺省参数使用注意事项分析

    2021-08-23 05:09:02
  • Jenkins配置maven项目之打包、部署、发布的全过程

    2023-08-07 19:14:29
  • 详解Python程序与服务器连接的WSGI接口

    2021-11-19 03:57:10
  • Anaconda3+tensorflow2.0.0+PyCharm安装与环境搭建(图文)

    2021-09-28 02:54:28
  • Python操作json数据的一个简单例子

    2022-10-23 17:09:37
  • ASP中转换unicode编码为gb2312函数

    2007-10-22 17:46:00
  • go实现脚本解释器gscript

    2023-10-12 00:49:39
  • asp之家 网络编程 m.aspxhome.com