import sys def binarize(file_in, file_out): """ Create a binary file from an ASCII file. Everything but '0' and '1' (alternatively '_' and 'X') is ignored from the input file. """ print ("binarizing " + file_in + " to "+ file_out + ".") try: f=open(file_in,'r') try: o=open(file_out,'wb') try: while True: b=readnext(f) if b==-1: break o.write(bytes([b])) except IOError: print("IOError happened during processing."); print("I am closing the input and ouput files and aborting."); print("Warning: The output file is very likely incomplete."); o.close() except IOError: print("IOError opening output file: " + file_out); f.close() except IOError: print("IOError opening input file: " + file_in); def readnext(f): """ Read next 'byte' from the given ASCII file (BufferedWriter) everything but '_','X','0','1' is ignored. Returns the byte as integer or -1 on EOF """ l=0 b="" while l<8: c=f.read(1) if not c: return -1 if c=="0" or c=='_': l+=1 b+="0" if c=="1" or c=='X': l+=1 b+="1" return int(b,2) def usage(): """ Prints usage information to sdtout """ print ("python3.x binarize.py [file_in] [file_out]") """ direct use """ if __name__ == "__main__": if(len(sys.argv)==3): binarize(sys.argv[1],sys.argv[2]) else: usage()