Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

I am using Python 2.7.3 and I am writing a script which prints the hex byte values of any user-defined file. It is working properly with one problem: each of the values are being printed on a new line. Is it possible to print the values with spaces instead of new lines?

For example, instead of

61 62

I would like to have 61 62.

Below is my code (..txt is a file which contains the text 'abcd'):

#!usr/bin/python 

import os 

import sys 

import time 

filename = raw_input("Enter directory of the file you want to convert: ") 

f = open(filename, 'rb') 

fldt = f.read() 

lnfl = len(fldt) 

print "Length of file is", lnfl, "bytes. " 

orck = 0 

while orck < lnfl: 

   bndt = hex(ord(fldt[orck])) 

   bndt = bndt[-2:] 

   orck = orck + 1 

   ent = chr(13) + chr(10) 

   entx = str(ent) 

   bndtx = str(bndt) 

   bndtx.replace(entx, ' ') 

   print bndtx

1 Answer

0 votes
by (106k points)

The below-mentioned code does almost everything you want:

f = open('data.txt', 'rb') 

while True: 

   char = f.read(1) 

   if not char: break 

   print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb') 

f.write("ab\r\ncd") 

f.close()

Output:-

61 62 0d 0a 63 64

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
2 answers
0 votes
1 answer
+2 votes
2 answers
+1 vote
2 answers
0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.7k users

Browse Categories

...