好久不在52发帖了,最近发生了很多事情,一直都没能静下心来学习。。。 这个代码是我以前学习python的时候看到的,感觉很不错,非常小巧,而且功能也很不错,这里就和大家一起分享下吧。。。 话说这里python的文章几乎没有啊 汗汗 - -|||||||
切割文件的代码(split.py):
import sys, os
kilobytes = 1024
megabytes = kilobytes * 1000
chunksize = int(1.4 * megabytes)
def split(fromfile, todir, chunksize=chunksize):
if not os.path.exists(todir):
os.mkdir(todir)
else:
for fname in os.listdir(todir):
os.remove(os.path.join(todir,fname))
partnum = 0
input = open(fromfile, 'rb')
while 1:
chunk = input.read(chunksize)
if not chunk:break
partnum = partnum + 1
filename = os.path.join(todir, ('part%4d' % partnum))
fileobj = open(filename, 'wb')
fileobj.write(chunk)
fileobj.close()
input.close()
assert partnum <= 9999
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? ')
todir = raw_input('Directory to store part files?')
else:
interactive = 0
fromfile, todir = sys.argv[1:3]
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')
合并文件的代码(join.py):
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')
在Windows SP3 + python 2.5下编译通过。
用法:
源代码:
源代码.zip
(1.42 KB, 下载次数: 8)
|