Writing huge strings in python

后端 未结 2 1121
离开以前
离开以前 2020-12-04 00:50

I have a very long string, almost a megabyte long, that I need to write to a text file. The regular

file = open(\"file.txt\",\"w\")
file.write(string)
file.c         


        
2条回答
  •  萌比男神i
    2020-12-04 01:27

    ok this is really not an answer it is more to prove your reasoning for the delay wrong

    first test write speed of a big string

     import timeit
     def write_big_str(n_bytes=1000000):
         with open("test_file.txt","wb") as f:
              f.write("a"*n_bytes)
     print timeit.timeit("write_big_str()","from __main__ import write_big_str",number=100)
    

    you should see a fairly respectable speed (and thats to repeat it 100 times)

    next we will see how long it takes to convert a very big number to a str

    import timeit,math
    n = math.factorial(200000)
    print timeit.timeit("str(n)","from __main__ import n",number=1)
    

    it will probably take ~10seconds (and that is a million digit number) , which granted is slow ... but not hours slow (ok its pretty slow to convert to string :P... but still shouldnt take hours) (well it took more like 243 seconds for my box i guess :P)

提交回复
热议问题