python中合并文件

#!/usr/bin/python import os,sys read_size=1024 def is_end_with(str1,str2): if len(str1)<len(str2): return 0 if str1[-len(str2):]==str2: return 1 return 0 def merge(from_dir,to_file): output=open(to_file,'wb') parts=os.listdir(from_dir); parts.sort() for file_name in parts: file_path=os.path.join(from_dir,file_name) if (not os.path.isfile(file_path)) or (not is_end_with(file_path,'.seg')): continue file_obj=open(file_path,'r'); while 1: file_bytes=file_obj.read(read_size) if not file_bytes: break output.write(file_bytes) file_obj.close() output.close() if __name__=='__main__': if len(sys.argv)==2 and sys.argv[1]=='-help': print 'Useage:merge.py [from_dir_name to to_file_name]' else: if len(sys.argv)!=3: interactive=1 from_dir=raw_input('dir containing parts files?') to_file=raw_input('name of file to be recretaed?') else: interactive=0 from_dir,to_file=sys.argv[1:] abs_from,abs_to=map(os.path.abspath,[from_dir,to_file]) print 'mergeing ',abs_from,' to make ',abs_to try: merge(from_dir,to_file); except: print 'err merging files:' print sys.exc_info()[0],sys.exc_info()[1] else: print 'merge complete:see ',abs_to if interactive: raw_input('pree enter key') 

你可能感兴趣的:(python,File,input,Path,merge,output)