Appending line to array in Python, String object has no attribute append

2.5k views Asked by At

I have two files, one containing 4 columns and multiple rows (input.xlxs) and one containing 1 column and the same number of rows (rms_date.out). I'm reading the rows from input.xlxs to an array and trying to append the 1 row corresponding row from rms_date.out to the array before writing to a new file.

When I try to append the line from rms_date.out to the array, I get an error that the appears to state that the array is of type String and doesn't have an append method and I'm confused:

    array[i].append(line)
AttributeError: 'str' object has no attribute 'append'

The following answer seems to suggest that what I'm doing should be possible: https://stackoverflow.com/a/16222978/1227362 however I'm obviously doing something wrong. Is it the fact that the above example is appending to the array object itself and I'm trying to append to a specific array index determined by the loop? Apologies I've only been working with Python for the first time the last couple of days.

My code is here (I haven't written the bit to write the appended array to a new file yet):

ins = open( "input.xlsx", "r" ) 
array = []
for line in ins:
    array.append(line)
file = open("rms_date.out", "r") 
for i in range(0, len(array)):
    for line in file:
        array[i].append(line)
        print array[i]
file.close()
ins.close()

Alo is there a simplier way to do what I'm proposing than outlined above?
Thanks, John!

1

There are 1 answers

0
ch3ka On

Well, strings indeed do not have an .append method, they are immutable in python.

You can use concatenation though:

array[i] += line