python打造简单文件切割机
好久不在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 == '-help':
print 'Use: split.py ]'
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
if len(sys.argv) == 4: chunksize = int(sys.argv)
absfrom,absto = map(os.path.abspath, )
print 'Splitting', absfrom, 'to', absto, 'by', chunksize
try:
parts = split(fromfile, todir, chunksize)
except:
print 'Error during split;'
print sys.exc_info(),sys.exc_info
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 == '-help':
print 'Use: join.py '
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
absfrom, absto = map(os.path.abspath, )
print 'Joining', absfrom ,'to make', absto
try:
join(fromdir, tofile)
except:
print 'Error joining files;'
print sys.exc_info(),sys.exc_info()
else:
print 'Join complete: see', absto
if interactive: raw_input('Press Enter key')
在Windows SP3 + python 2.5下编译通过。
用法:
源代码:
想学的东西,仔细数一数,实在有很多了
。。。不过还是来支持则个 膜拜啊,不懂python啊,杯具了~~ 正想学习呀,来看看 正想学习,想找一个读文件的方法,用“。”号分割分段读取文件。 不错,支持一下,python就是搭建环境太麻烦了
页:
[1]