I have the following list that has been read in from a file: films.txt
['0,Genre, Title, Rating, Likes', '1,Sci-Fi,Out of the Silent Planet, PG, 0', '2,Sci-Fi,Solaris, PG,0', '3,Sci-Fi,Star Trek, PG, 0', '4,Sci-Fi,Cosmos, PG, 0', '5,Drama, The English Patient, 15, 0', '6,Drama, Benhur, PG, 0', '7,Drama, The Pursuit of Happiness, 12, 0', '8,Drama, The Thin Red Line, 18, 0', '9,Romance, When Harry met Sally, 12, 0', "10,Romance, You've got mail, 12, 0", '11,Romance, Last Tango in Paris, 18, 0', '12,Romance, Casablanca, 12, 0']
I need to access a specific field (namely the "likes"
) based on an index number of the film. For instance the output for
print("PRINT THE CURRENT FILM ROW", allfilms[3])
print("PRINT THE CURRENT LIKES", allfilms[4])
is:
PRINT THE CURRENT FILM ROW 3,Sci-Fi,Star Trek, PG, 0
PRINT THE CURRENT LIKES 4,Sci-Fi,Cosmos, PG, 0
What I want to access however is, the 0
, in the third row. That is the 4th field in the third row (or second row), depending on the index number so I'd need an if
or loop
here.
I tried:
print("PRINT THE CURRENT FILM ROW", allfilms[3][4])
which outputs a character rather than a field....
i
It is reading the "i" character in Sci-fi which is the fourth character along ....
As mentioned, I need the fourth FIELD (the 0). Any thoughts?
Based on the suggestions below, I tried:
def likeafilm(x,username):
#prompt the user to enter the ID number they require
idnumber=int(input("To confirm, please enter the number of the film you wish to like:"))
#create a list which stores and displays all the data in the films txt file
with open("films.txt",mode="r") as f:
allfilms=[]
#allfilms=list(csv.reader(allfilms)) - this does not clean the extra spaces so try the next line
allfilms=[[x.strip() for x in row] for row in csv.reader(allfilms)]
print(allfilms[3])
allfilms[3][4]=str(int(allfilms[3][4])+1)
print(allfilms)
but it produces the following error:
print(allfilms[3])
IndexError: list index out of range
Also, I need to use an idnumber instead of 3. (as seen in the function above)
print(allfilms[idnumber])
same error:
print(allfilms[idnumber])
IndexError: list index out of range