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

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

我一直收到这个错误,我不知道它是什么意思。我已采取措施摆脱代码中的元组。该程序应该读取包含一系列数字的文档,然后使用冒泡排序功能对这些数字进行排序,然后将旧列表和新的排序列表打印到新文件中。 我的任务是创建一个新文件并打印给定文件中的原始数组,以及使用冒泡排序函数排序的排序数组,作为逗号分隔文件中的两行。

# 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() ```

而不是在你的行中创建一个新文件:

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

您通过在括号之间声明这些逗号分隔值来定义包含两个字符串“Sorted.csv”和“w+”的元组。与其在代码顶部创建 newFile,不如等到真正打算填充它时再创建它。

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

我怀疑您可能会遇到问题,因为您的 newFile 正在按您想要的方式格式化,但如果这是真的,我会让您提出一个新问题。