hen shalom
hen shalom

Reputation: 147

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 ?

Upvotes: 4

Views: 31036

Answers (2)

ands
ands

Reputation: 2046

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.

Upvotes: 7

Jordan Bonitatis
Jordan Bonitatis

Reputation: 1547

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)

Upvotes: 8

Related Questions