Search code examples
pythonfilesortingbubble-sort

AttributeError: 'tuple' object has no attribute 'write' Error


I keep getting this error and I have no idea what it means. I have taken measures to get rid of a tuple in my code. The program is supposed to read in a document which has a series of numbers and then sort those numbers using a bubble sort function and then print the old list and the new, sorted list onto a new file. My assignment is to create a new file and print the original array, from the given file, and the sorted array, sorted using a bubble sort function, as two lines in a comma separated file.

# reading in the document into the program
file = open("rand_numb.csv", "r")
# creating a new file that will have the output printed on it
newFile = ("SORTED.csv", "w+")
# creating a blank list that will hold the original file's contents
orgArr = []
# creating the bubblesort function
def bubblesort(arr):
    # creating a variable to represent the length of the array
    length = len(arr) 
    # traverse through all array elements 
    for i in range(length): 
        # last i elements are already in place 
        for j in range(0, length-i-1): 
            # traverse the array from 0 to length-i-1 and swap if the element found is greater than the next element
            if arr[j] > arr[j+1] : 
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr
# Prog4 Processing
# using a for loop to put all of the numbers from the read-in file into a list
listoflists = [(line.strip()).split() for line in file]
# closing the original file
file.close()
# creating a variable to represent the length of the list
listLen = len(listoflists)
# using a for loop to have the elements in the list of lists into one list
for num in range(0, listLen):
    orgArr.append(num)
# using list function to change the tuple to a list
orgArr = list(orgArr)
# using the bubblesort function
sortArr = bubblesort(orgArr)
# Prog4 Output
# outputting the two lists onto the file
newFile.write(orgArr + "\n")
newFile.write(sortArr)
# closing the new file
newFile.close() ```

Solution

  • Rather than create a new file in your line:

    newFile = ("Sorted.csv", "w+")
    

    you have instead defined a tuple containing two strings "Sorted.csv" and "w+" by declaring these comma separated values between parenthesis. Rather than create your newFile at the top of your code, you can wait to create it until you actually intend to populate it.

    with open("Sorted.csv", "w+") as newFile:
        newFile.write(orgArr + "/n")
        newFile.write(sortArr)
        newFile.close()
    

    I suspect you may have issues that your newFile is formatting how you want, but I will let you raise a new question in the event that that is true.