繁体   English   中英

AttributeError: 'tuple' object has no attribute 'write' 错误

[英]AttributeError: 'tuple' object has no attribute 'write' Error

我不断收到此错误,我不知道这意味着什么。 我已采取措施删除代码中的元组。 该程序应该读取具有一系列数字的文档,然后使用冒泡排序 function 对这些数字进行排序,然后将旧列表和新排序列表打印到新文件中。 我的任务是创建一个新文件并打印来自给定文件的原始数组,以及使用冒泡排序 function 排序的排序数组,作为逗号分隔文件中的两行。

# 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 正在格式化您想要的格式,但如果这是真的,我会让您提出一个新问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM