4

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 ?

pppery
  • 3,731
  • 22
  • 33
  • 46
hen shalom
  • 127
  • 1
  • 1
  • 9

2 Answers2

7

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)

Jordan Bonitatis
  • 1,527
  • 14
  • 12
7

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

with open('textfile.txt', 'w') as textfile:
    textfile.write(a)

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.

Christoph H.
  • 173
  • 1
  • 14
ands
  • 1,926
  • 16
  • 27