Search code examples
pythonpython-3.xsortingnumbersbubble-sort

Using bubble sort inside a .txt file


x = open("C:\\Users\\User\\Documents\\original.txt", 'r')

mylist = x.read()
length = len(mylist)
for y in range(length):
    for q in range(length-1):
        if mylist[q] > mylist[q+1]:
            mylist[q], mylist[q+1] = mylist[q+1], mylist[q]
            print (mylist)

Traceback (most recent call last):

File "<pyshell#12>", line 4, in <module>

mylist[q], mylist[q+1] = mylist[q+1], mylist[q]

TypeError: 'str' object does not support item assignment

Can someone explain this error please, thanks.


Solution

  • What you're trying to do is equivalent to:

    string = "Some string"
    string[0], string[1], = string[1], string[0]
    

    i.e. You're trying to modify the character inside the string.

    What you want to do is either
    a) Split the contents into a list of words using mylist.split().
    b) Use x.readlines() to read the file a list of lines, and sort those.
    c) Split the entire file into a list of characters with [x for x in mylist] and sort the characters,

    Then use ''.join(list_of_whatever) to turn the list back into a string.