Smajjk
Smajjk

Reputation: 394

Writing from a large list to a text file in Python

Something strange happens when I try to write from a ordinary list, containing 648470 string-values, to a text file.

    textFile = open('bins.txt', 'w')

    for item in bigList:
        print item # This prints fine
        textFile.write(item)

    textFile.close()

The text file grows rapidly in file size and is filled with all kind of symbols, not the intended ones... Even if I just write a small span of the content of bigList the text file gets corrupted. If I do the exact same thing with a much smaller list, there's no problem. Is the large size of the list causing this problem? The output of print(bigList[:10]) is

['167', '14444', '118', '22110', '118', '8134', '82', '8949', '7875', '171']

Upvotes: 0

Views: 5163

Answers (2)

Steven
Steven

Reputation: 195

It is possible that the file is having problems writing because some of the list objects are not strings. Try:

textFile = open('bins.txt', 'w')

for item in bigList:
    print item # This prints fine
    textFile.write(str(item))

textFile.close()

However I cannot see your list so I do not know for certain if this is an actual problem.

Upvotes: 0

LtWorf
LtWorf

Reputation: 7600

It works absolutely fine to me.

In your code you are forgetting to close the file, and also, since you open the file in append mode, my guess is that you have some garbage in the file that was there and you forgot to remove.

Also, keep in mind that the write in that way will not separate the numbers in any way.

Upvotes: 1

Related Questions