Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Saving long string in text file

I have a long string that I want to save in a text file with the code:

taxtfile.write(a)

but because the string is too long, the saved file prints as:

"something something ..... something something"   

how do I make sure it will save the entire string without truncating it ?

like image 577
hen shalom Avatar asked Dec 18 '22 15:12

hen shalom


2 Answers

it should work regardless of the string length

this is the code I made to show it:

import random

a = ''
number_of_characters = 1000000
for i in range(number_of_characters):
    a += chr(random.randint(97, 122))
print(len(a))       # a is now 1000000 characters long string

textfile = open('textfile.txt', 'w')
textfile.write(a)
textfile.close()

you can put number_of_characters to whatever number you like but than you must wait for string to be randomized

and this is screenshot of textfile.txt: http://prntscr.com/bkyvs9

probably your problem is in string a.

like image 56
ands Avatar answered Dec 21 '22 10:12

ands


I think this is just a representation in your IDE or terminal environment. Try something like the following, then open the file and see for yourself if its writing in its entirety:

x = 'abcd'*10000
with open('test.txt', 'w+') as fh:
    fh.write(x)

Note the the above will write a file to whatever your current working directory is. You may first want to navigate to your ~/Desktop before calling Python.

Also, how are you building the string a? How is textfile being written? If the call to textfile.write(a) is occurring within a loop, there may be a bug in the loop. (Showing more of your code would help)

like image 38
Jordan Bonitatis Avatar answered Dec 21 '22 10:12

Jordan Bonitatis