用Python将十六进制数字写入文件

时间:2018-10-10 09:23:22

标签: python python-3.x

以下代码正在读取一个名为“ test.txt”的文件,该文件具有十六进制数字。下面的代码将这些十六进制数转换为十进制数。如何将十进制数写入文件而不是打印出来?

我的代码

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

2 个答案:

答案 0 :(得分:0)

实际上built in print function有一个file关键字参数。您可以使用它将输出重定向到您选择的文件。

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

假设您有test.txt,其中包含以下内容:

ff
10

然后out.txt将包含:

255
16

从python 2.7或python 3.1开始,您甚至可以将这两个与语句组合

...
with open(input_file, 'r') as fp, open(output_file, 'w') as out_fp:
    ...

答案 1 :(得分:0)

 fp = open("file.txt", "w")
 fp.write("your data") 

应该工作。