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

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

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.

Related

Im having difficulty utilizing an array in python

I'm trying to manipulate text from a word file however when I save it to an array of classes, all the indexes are being overwritten instead of the one particular index I intend to change.
for line in modified:
if line.startswith('Date'):
output.append(line)
list2=line.split(' ')
work.date=list2[1]
# print(work.date)
if line.startswith('PPV'): #list1[2]=l,[3]=t,[4]=v
output.append(line)
list1=line.split(' ')
work.lpv=list1[2]
# print("l is ",list1[2],work.lpv)
work.tpv=list1[3]
# print("t is ",list1[3],work.tpv)
work.vpv=list1[4]
# print("v is ",list1[4],work.vpv)
daylist[count]=work
#print("l2 is ",list1[2],work.lpv)
#print("daylist", count, "saved")
print(count,daylist[count].date) #this displays the correct value at the propper index but all other indexs have also been changed to this value
count+=1
Im trying to save a class which holds a string and a few floats to an array but cannot seem to get it to save to each index properly as it is read from the file. ive tried messing with the scope and list initialization but cant seem to figure it out. Any input would be appreciated, Thanks!
Every index in the daylist array references the same work object. When you change an attribute of work (e.g. work.date) it's reflected in all references to that single object. You want each index to reference a separate, independent object but that's not what the code is doing.
Try something like this where work is a dictionary:
for line in modified:
work = {} # <-- this makes the name "work" refer to a new, empty dict
if line.startswith('Date'):
output.append(line)
list2=line.split(' ')
work["date"] = list2[1]
elif line.startswith('PPV'):
output.append(line)
list1=line.split(' ')
work["lpv"] = list1[2]
# ...
print(count, daylist[count]["date"])
count += 1
Here's a helpful link on how names reference objects: How does Python referencing work?

issue with Looping through lists to write new rows in a csv file using python

I am trying to add content to my existing csv file. meaning I would not like to remove any existing content but just like to add new lines based on list of lists.
However, in the final output I don't see any new row being added in the csv. Also the variable is returning empty list values (please see the comment on the code line).
Here i am asking the user first the number of entries. then value for each entry (each row value for each column). Then I am simple appending it to a final list i.e total_number_of_rows which should look like:
[[x,x,x][xy,xy,xy].
In the final code I am trying to write the values from the two lists to the CSV file for example the final output should look like:
id, name, color
oldvalue1, oldvalue2, oldvalues3 #assuming this is an already existing row in the csv file
x,x,x
xy,xy,xy
number_of_entries = int(input("how many entries will you need to enter:"))
each_new_row = []
total_number_of_rows = []
for i in range(number_of_entries):
new_id = input("add new new_id")
new_name = input ("add new date")
new_color = input ("add new color")
each_new_row.extend((new_id,new_name,new_color))
print("each_new_row",each_new_row)
total_number_of_rows.append(each_new_row)
print("total number of rows", total_number_of_rows) # this is showing [[1,1,red],[2,2,blue]]
each_new_row.clear()
print("total_number_of_rows", total_number_of_rows) ## this is showing [[],[]]
with open('file.csv', 'a',newline ="") as f:
writer = csv.writer(f)
writer.writerows(total_number_of_rows)
#not seeing any new row added
each_new_row = []
# ...
for i in range(number_of_entries):
# ...
total_number_of_rows.append(each_new_row)
# ...
each_new_row.clear()
This appends the same list multiple times to total_number_of_rows. At the end you clear this list, and that's why total_number_of_rows contains only empty lists (it's the same empty list multiple times).
Instead, you want to create a new empty list in every iteration instead of reusing the same list over and over.
for i in range(number_of_entries):
each_new_row = [] # do this
# ...
total_number_of_rows.append(each_new_row)
# ...
#each_new_row.clear() # don't do this

Python create new array for different iteration of a for loop

I want to create a new array (or list) for every iteration. Here is my code:
import numpy as np
data2 = open('pathways.dat', 'r', errors = 'ignore')
pathways = data2.readlines()
special_line_indexes = []
PWY_ID = []
line_cont = []
L_PRMR = [] #Left primary
#i is the line number (first element of enumerate), while line is the line content (2nd elem of enumerate)
for CUI in just_compound_id:
for i,line in enumerate(pathways):
if '//' in line:
#fint the indexes of the lines containing //
special_line_indexes = i+1
elif 'REACTION-LAYOUT -' in line:
if CUI in line:
PWY_ID.append(special_line_indexes)
Specifically I want to create a different array PWY_ID for a different iteration of CUI (the first foor loop). What I end up is instead a long array with all the output. Maybe it would be more efficient to use a dictionary, but I am not sure how to implement it in a for loop...
You can start mapping out the data schema you want. Decide what would be key and what would be value.
Then, you can start by creating a dict()
foo = dict()
And you insert items into dictionary by
foo["KEY"] = "VALUE"
for example,
foo["x"] = 12
then, the value will be stored in the dictionary.
Here is a tutorial about how to use dictionary in python:
https://www.youtube.com/watch?v=2j7ox_zqM4g

.split from a file and putting it in an array

Im reading a file with some information and each part is separated with a # however on each line i want it to be a different array so i did this and im not sure why its not working.
main_file = open("main_file.txt","r")
main_file_info=main_file.readlines()
test=[]
n=0
for line in main_file_info:
test[n]=line.split("#")
test=test[n][1:len(test)-1] # to get rid of empty strings at the start and the end
print(test)# see what comes out
main_file.close()
The way you are inserting the output of line.split("#") in your list is wrong. Your list is not initialized, hence, you can't simply assign anything to any element of the list. So, what you need to do is this :
test.append(line.split("#"))
Or, you can initialize your list as below :
test = [[]]*(len(main_file_info))
test = [None for _ in range(total)]
# instead of test = []
or simply just append to test:
test.append( line.split("#") )

Python list index not found in loading list from text file

The assignment was to get a user to input 4 numbers, then store them in a text file, open that text file, show the 4 numbers on different lines, then get the average of those numbers and display it to the user.
Here is my code so far:
__author__ = 'Luca Sorrentino'
numbers = open("Numbers", 'r+')
numbers.truncate() #OPENS THE FILE AND DELETES THE PREVIOUS CONTENT
# Otherwise it prints out all the inputs into the file ever
numbers = open("Numbers", 'a') #Opens the file so that it can be added to
liist = list() #Creates a list called liist
def entry(): #Defines a function called entry, to enable the user to enter numbers
try:
inputt = float(input("Please enter a number")) #Stores the users input as a float in a variable
liist.append(inputt) #Appends the input into liist
except ValueError: #Error catching that loops until input is correct
print("Please try again. Ensure your input is a valid number in numerical form")
entry() #Runs entry function again to enable the user to retry.
x = 0
while x < 4: # While loop so that the program collects 4 numbers
entry()
x = x + 1
for inputt in liist:
numbers.write("%s\n" % inputt) #Writes liist into the text file
numbers.close() #Closes the file
numbers = open("Numbers", 'r+')
output = (numbers.readlines())
my_list = list()
my_list.append(output)
print(my_list)
print(my_list[1])
The problem is loading the numbers back from the text file and then storing each one as a variable so that I can get the average of them.
I can't seem to find a way to specifically locate each number, just each byte which is not what I want.
Your list (my_list) has only 1 item - a list with the items you want.
You can see this if you try print(len(my_list)), so your print(my_list[1]) is out of range because the item with index = 1 does not exist.
When you create an empty list and append output, you are adding one item to the list, which is what the variable output holds for a value.
To get what you want just do
my_list = list(output)
You'll have two main problems.
First, .append() is for adding an individual item to a list, not for adding one list to another. Because you used .append() you've ended up with a list containing one item, and that item is itself a list... not what you want, and the explanation for your error message. For concatenating one list to another .extend() or += would work, but you should ask yourself whether that is even necessary in your case.
Second, your list elements are strings and you want to work with them as numbers. float() will convert them for you.
In general, you should investigate the concept of "list comprehensions". They make operations like this very convenient. The following example creates a new list whose members are the respectively float()ed versions of your .readlines() output:
my_list = [float(x) for x in output]
The ability to add conditionals into a list comprehension is also a real complexity-saver. For example, if you wanted to skip any blank/whitespace lines that had crept into your file:
my_list = [float(x) for x in output if len(x.strip())]
You can change the end of your program a little and it will work:
output = numbers.readlines()
# this line uses a list comprehension to make
# a new list without new lines
output = [i.strip() for i in output]
for num in output:
print(num)
1.0
2.0
3.0
4.0
print sum(float(i) for i in output)
10

Categories

Resources