如何更快地在文本文件中写数字?

问题描述 投票:0回答:1

我编写了一个程序,生成一个数字需要花费0.1092秒,但是将这个数字(3.81 MB)写入文本文件中/上面需要787.26012秒= 13分钟。

import time
import sys
import math
start = time.time()

input_file="First1_58MB_enwik9.txt"
with open(input_file, "rb") as file: #--> open file in binary read mode
  byte_obj = file.read() #--> read all binary data
g=int.from_bytes( byte_obj, byteorder=sys.byteorder)
binary_dt=bin(g)


int_v=int(binary_dt,2)
length = math.ceil(math.log(int_v, 256))
res = int.to_bytes(int_v, length=length, byteorder='little', signed=False)

open("output_file_2.txt", "wb").write(res)

end = time.time()
print("Total time (in seconds) = ",(end - start))
#---------------------------
start = time.time()
with open("output_file_1.txt", 'w') as f:
  f.write('%d' % g)

end = time.time()
print("Total time (in seconds) = ",(end - start))

是否有更快的方法可以在文本文件中写入大量数字?

此外,如果我将数字写在另一种文件中会更快,比如说我将数字写为二进制文件还是不带扩展名的文件?

PS:没有扩展名的文件是什么?

python file-io filesystems fwrite
1个回答
0
投票

使用下面的代码,我能够在一秒钟内生成30mb的文件。

s = "hey"*10000000 # multiply "hey" 10000000 times and then return the string
with open("output_file_1.txt", 'w') as f:
    f.write(s)

是否有必要明确告知python我们正在写入.txt文件的对象是整数?如果否,那么...

g视为字符串而不是数字,然后将代码更改为f.write(g)。然后检查您是否发现时间有所改善。

© www.soinside.com 2019 - 2024. All rights reserved.