Shawn Dooley Shawn Dooley - 1 month ago 8
Python Question

Appending to a list from a for loop (to read a text file)

How do I append to an undetermined list from a for loop?
The purpose is to first slice each line by '-'. Then I would like to append these slices to an array without a determined size. I have the following code, and am loosing hair because of how simple this seems!

Each line in the text file looks like the following:
2014-06-13,42.7,-73.8,27

program so far:

f = open('Lightning.txt')

lightning =list()

for templine in f:

if not templine.startswith('2014'): continue

templine = templine.rstrip('-')

line = templine.split()

print line[2]


Thank you community,

Answer

Try something like that if you want to get list of formated strings.

f = open('Lightning.txt')
lightning =list()
for templine in f:
    if not templine.startswith('2014'): continue
    # We are splitting the line by ',' to get [2014-06-13, 42.7,-73.8, 27]
    templine = templine.split(',')
    # After splitting is done, we know that at the 1st place is the date, 
    # and at the last one is the number of video recordings.

    #Here we asign the first item to "data" and the last one to "num_of_strikes"
    date, num_of_strikes = templine[0], templine[-1]
    # After that is done, we create the output string with placeholders 
    # {data} and {num} waiting for data to be passed
    output = '{date} : {num} lightning strikes were recorded.'
    # Here we are appending the formated string, passing our data to placeholders
    # And yes, they work like a dictionary, so u can write (key = value)
    lightning.append(output.format(date= date, num= num_of_strikes))