-3

The below code is reading a file called ‘test.txt’ which has hex numbers. The below code is converting these hex number into decimal numbers. How can I write the decimal number to a file instead of printing it out?

my code

file= 'test.txt'

with open(file) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       i = int(line, 16)
       print(str(i))
       line = fp.readline()
       cnt += 1
bereal
  • 32,519
  • 6
  • 58
  • 104
rich dave
  • 57
  • 1
  • 7

2 Answers2

0

Actually the built in print function has a file keyword argument. You can use this to redirect your output to a file of your choice.

input_file = 'test.txt'
output_file = 'out.txt'

with open(input_file, 'r') as fp:
    with open(output_file, 'w') as out_fp:
        line = fp.readline()
        cnt = 1
        while line:
            i = int(line, 16)
            print(str(i), file=out_fp)
            line = fp.readline()
            cnt += 1

Assuming you have test.txt with the following content:

ff
10

Then out.txt will contain:

255
16

As of python 2.7 or python 3.1 you can even combine those two with statements

...
with open(input_file, 'r') as fp, open(output_file, 'w') as out_fp:
    ...
kalehmann
  • 4,821
  • 6
  • 26
  • 36
0
 fp = open("file.txt", "w")
 fp.write("your data") 

should work.

bakarin
  • 622
  • 5
  • 17