I have a CSV file about satellites that I need to iterate through a for loop to find out, among other things, how many 'Civilian' satellites the file has. The problem is that when I want to access some specific data I usually get TypeError: object is not subscriptable or TypeError: string indices must be integers.
So far I have done the following:
satelites = open("UCS-Satellite-Database.csv")
for i in satelites:
print(i)
I have done this to see the rows of the file. So far so good. The problem comes when I want to iterate over the 'Civil' variable or, also, over a specific column, because it always gives me an error. For this I am putting the following:
For the 'Civilian' variable:
for i in satelites:
print(i['Civil'])
For the second column of the file, which is called 'Users':
for i in satelites:
print(i['Users'])
Both loops give me error. I have also tried other ways to iterate but with the same error result. If anyone knows what could be wrong and tells me I would appreciate it.
Using the function
open
you are opening the file in text mode, so, in your case, when iterating over the variablesatelites
you are iterating over each line of text in the file.In this case, the only thing you can do is skip the first line, which is the one that contains the headers, for example using
satelites = open("UCS-Satellite-Database.csv")[1:]
and then use the functionsplit
with the separator that is in your CSV file (usually ',' or ';') over each line of text (the variablei
in your case) to separate the line into the different elements defined in the header.Processing a CSV (or any text file) by hand is tedious, that's why there are libraries that handle common formats such as csv, json or yml.