Dominik Praski Dominik Praski - 7 days ago 6
Python Question

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

Answer

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))
Comments