Python实现分割文件及合并文件的方法
作者:Sephiroth 发布时间:2022-01-28 00:02:02
标签:Python,分割,合并,文件
本文实例讲述了Python实现分割文件及合并文件的方法。分享给大家供大家参考。具体如下:
分割文件split.py如下:
#!/usr/bin/python
##########################################################################
# split a file into a set of parts; join.py puts them back together;
# this is a customizable version of the standard unix split command-line
# utility; because it is written in Python, it also works on Windows and
# can be easily modified; because it exports a function, its logic can
# also be imported and reused in other applications;
##########################################################################
import sys, os
kilobytes = 1024
megabytes = kilobytes * 1000
chunksize = int(1.4 * megabytes) # default: roughly a floppy
def split(fromfile, todir, chunksize=chunksize):
if not os.path.exists(todir): # caller handles errors
os.mkdir(todir) # make dir, read/write parts
else:
for fname in os.listdir(todir): # delete any existing files
os.remove(os.path.join(todir, fname))
partnum = 0
input = open(fromfile, 'rb') # use binary mode on Windows
while 1: # eof=empty string from read
chunk = input.read(chunksize) # get next part <= chunksize
if not chunk: break
partnum = partnum+1
filename = os.path.join(todir, ('part%04d' % partnum))
fileobj = open(filename, 'wb')
fileobj.write(chunk)
fileobj.close() # or simply open().write()
input.close()
assert partnum <= 9999 # join sort fails if 5 digits
return partnum
if __name__ == '__main__':
if len(sys.argv) == 2 and sys.argv[1] == '-help':
print 'Use: split.py [file-to-split target-dir [chunksize]]'
else:
if len(sys.argv) < 3:
interactive = 1
fromfile = raw_input('File to be split? ') # input if clicked
todir = raw_input('Directory to store part files? ')
else:
interactive = 0
fromfile, todir = sys.argv[1:3] # args in cmdline
if len(sys.argv) == 4: chunksize = int(sys.argv[3])
absfrom, absto = map(os.path.abspath, [fromfile, todir])
print 'Splitting', absfrom, 'to', absto, 'by', chunksize
try:
parts = split(fromfile, todir, chunksize)
except:
print 'Error during split:'
print sys.exc_info()[0], sys.exc_info()[1]
else:
print 'Split finished:', parts, 'parts are in', absto
if interactive: raw_input('Press Enter key') # pause if clicked
合并文件join_file.py如下:
#!/usr/bin/python
##########################################################################
# join all part files in a dir created by split.py, to recreate file.
# This is roughly like a 'cat fromdir/* > tofile' command on unix, but is
# more portable and configurable, and exports the join operation as a
# reusable function. Relies on sort order of file names: must be same
# length. Could extend split/join to popup Tkinter file selectors.
##########################################################################
import os, sys
readsize = 1024
def join(fromdir, tofile):
output = open(tofile, 'wb')
parts = os.listdir(fromdir)
parts.sort()
for filename in parts:
filepath = os.path.join(fromdir, filename)
fileobj = open(filepath, 'rb')
while 1:
filebytes = fileobj.read(readsize)
if not filebytes: break
output.write(filebytes)
fileobj.close()
output.close()
if __name__ == '__main__':
if len(sys.argv) == 2 and sys.argv[1] == '-help':
print 'Use: join.py [from-dir-name to-file-name]'
else:
if len(sys.argv) != 3:
interactive = 1
fromdir = raw_input('Directory containing part files? ')
tofile = raw_input('Name of file to be recreated? ')
else:
interactive = 0
fromdir, tofile = sys.argv[1:]
absfrom, absto = map(os.path.abspath, [fromdir, tofile])
print 'Joining', absfrom, 'to make', absto
try:
join(fromdir, tofile)
except:
print 'Error joining files:'
print sys.exc_info()[0], sys.exc_info()[1]
else:
print 'Join complete: see', absto
if interactive: raw_input('Press Enter key') # pause if clicked
希望本文所述对大家的Python程序设计有所帮助。


猜你喜欢
- 返回被去除指定字符的字符串默认去除空白字符删除首尾字符:str.strip([char]) 删除首字符:str.lstrip([char])
- 简述小编经常会遇到一些数据库编码不对得问题,好TM头疼,这里做一个记录,供大家参考。修改数据库字符集:ALTER DATABASE db_n
- 最近想备份网站,但是php下载文件的大小是有大小限制的,而我也懒得装ftp再下载了,就想着暂时弄个二级域名站,然后用python(pytho
- 在pytorch框架中,关于日志的保存,其中一种方式就是借鉴使用了tensorboard的库。所以我们需要在环境中安装tensorboard
- 通过将身份认证令牌直接传给 API 服务器,可以避免使用 kubectl 代理,像这样:使用 grep/cut 方式:# 查看所有的集群,因
- 压测时,图片太少,想着下载网页中的图片,然后过滤指定分辨率,但网页中指定分辨率的图片太少了(见下) 后使用格式工厂转换图片import ur
- 文件结构html_downloader.py - 下载网页html内容#!/usr/bin/python# -*- coding: UTF-
- 我们在使用bootstraptable做表格展示时,有时需要固定表格的高度当数据超出高度会出现滚动条,这时有可能出现表头列和数据列对不齐。出
- 一、Python+unittest+requests+HTMLTestRunner 完整的接口自动化测试框架搭建_00——框架结构简解&nb
- 在项目过程中,我们常常需要获取IP的所在地。而这一功能一般都是通过一些数据网站的对外接口来实现,这些接口一般情况下都是付费使用的。在这篇文章
- 创建一个apps包 专门来放子应用创建users子应用 处理用户事务追加导包路径在settings中用 print(sys.path) 查看
- 前几天有个同学想了解下如何在go-micro中做链路跟踪,这几天正好看到wrapper这块,wrapper这个东西在某些框架中也称为中间件,
- 一、前言最近做web网站的测试,遇到很多需要批量造数据的功能;比如某个页面展示数据条数需要达到10000条进行测试,此时手动构造数据肯定是不
- 在做前端界面开发的时候,遇到需要改变颜色的需求,就需要使用颜色选择器。针对这个问题,第一想法,自然是H5提供了input color,可以实
- 利用上一篇的框架,再写了个翻转棋的程序,为了调试minimax算法,花了两天的时间。几点改进说明:拆分成四个文件:board.py,play
- 某天写代码突然县道这个问题,顺势总结一波JavaScript 函数和变量声明的“提前”(hoist)行为简单的说 如果我们使用 匿名函数va
- 用6N±1法求素数 任何一个自然数,总可以表示成为如下的形式之一: 6N,6N+1,6N+2,6N+3,6N+4,6N+5 (N=0,1,2
- 现在需要一个写文件方法,将selenium的脚本运行结果写入test_result.log文件中首先创建写入方法def write_resu
- 本文实例讲述了Python实现希尔排序算法的原理与用法。分享给大家供大家参考,具体如下:希尔排序(Shell Sort)是插入排序的一种。也
- 1.条件语句几个注意点和C#不一样的。if a < 5 { return 0} else {