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程序设计有所帮助。
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- 前言其实就是个小问题,但是爆出来的时候也很莫名其妙。因为之前都跑得好好的,只是换了不同的文件去跑才出的问题,关键是不同的文件要处理的内容和格
- 一位资深的设计师曾经向我抱怨,说老板不仅让他做“设计”工作,还让他做“制作”工作,真是很烦。言下之意,“制作”还要一个资深设计师亲自上阵,未
- Python应用编程需要用到的针对不同数据库引擎的数据库接口:http://wiki.python.org/moin/DatabaseInt
- 今天不小心又点了收藏夹里Google的新首页风格的地址,赫然发现又变了!从这个页面上线以来,偶尔会去看看,短短一年的时间,已经变换了至少三次
- 学习目的: 掌握文本框的用法 初次接触try…catch…语法 今天内容很轻松,用一个例子,输入年月日,判断输入是否正确 图片如下: 用个
- 原文地址:30 Days of Mootools 1.2 Tutorials - Day 5 - Event HandlingMooTool
- 先不说直接改后缀,直接可以用网快等工具直接下载,其实这样你已经是为入侵者打开了大门。入侵者可以利用asp/asa为后缀的数据库直接得到web
- 在设计网页时,经常遇到某些页面需限权访问的情况。比如,一个公司的某些产品只让某一或某些供应商或客户浏览。那么,我们如何实现这一功能呢?本文,
- 前言数据处理过程中,经常会遇到数据有缺失值的情况,本文介绍如何用Pandas处理数据中的缺失值。一、什么是缺失值对数据而言,缺失值分为两种,
- PHP+MySQL的组合是构建网站的一个常见搭配,不过如何使用PHP通过Web访问MySQL数据库呢?下面从Web数据库架构的工作原理讲起。
- 斐波那契记忆优化法:<script type="text/javascript">var fibonacci
- 不同的数字之间使用 空格“ ”,“$”,"*"等隔开,支持带小数点的字符串NumArray=str2num(LineSt
- 1.线性与非线性回归线性回归 Linear Regression:两个变量之间的关系是一次函数关系的—&mdas
- 什么情况下用响应缓冲会提高运行速度?例1、脚本引擎与 HTML 之间的切换频繁,对响应流写操作太多,导致性能下降:<table>
- 这里我们将分析一下如何开启和使用smarty缓存,如何清除smarty缓存以及smarty的全局缓存,部分缓存,局部缓存三种缓存机制。一、开
- 斜角导航条看上去立体感比较强,但实现起来比较麻烦;这是前几天写的一个测试代码,实现时,本来想用简单的图片加负数来实现;但GIF图片对半透明的
- 在我们开始一个项目的设计的时候,脑子里肯定有无数的构想。是做视觉冲击强烈、夺人眼球的绚丽风格?还是复古的拼贴风?又或者目前最in的极简主义设
- Google Chrome 的发布,使我们更加的注重基于 WebKit 核心的浏览器的表现情况,但我们很多时候“不小心”就会出现问题。考虑下
- 他们是如何不让我的Teleport和Webzip工作的?你也可以做得到哦: <%dim UserAgentUser
- rs.open sql,conn,A,B A: ADOPenforwardonly (=0) 只读,且当前数据记录只能向下移动。 ADOPe