0

Basically, this is what I am trying to do. I have an CSV file that I read in using Python 3. So, here is the basic layout of the rows:

Row1: On
Row2: <empty>
Row3: <empty>
Row4: On
Row5: On
Row6: <empty>
Row7: Off
Row8: <empty>

The code to access this would be:

for row in file:
     var = row[0]
     print(var)

The output I would like to see for each line after running the script would be:

for row in file:
     print(var)

On
On
On
On
On
On
Off
Off

I am not sure how to do it, but I am trying to keep track of the variable as the program moves through the for loop. Here is the logic:

for loop:
  1.  If row[0] has the string 'On', then assign 'On' to var
  2.  If the next row[0] is empty, then I want the var to retain the previous value of 'On'.
  3.  Var will not change from 'On' until row[0] has a different value such as 'Off'.  Then, Var will be assigned 'Off'.

Hopefully this question makes sense. I am not sure how to do this in Python 3.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • What do you mean when you say a row is empty? A blank line? Commas with no values between them? Empty strings? – Mark Reed Nov 01 '15 at 00:33
  • 2
    So just declare `var = None` outside the loop? Then, `if row != "": var = row`? Or am I missing something? – Teepeemm Nov 01 '15 at 00:33

2 Answers2

1
# set an initial value for `var`
var = None
for row in file:
    # `row` should now contain the text content of a line
    if row:
        # if the string is not empty
        # set var to the value of the string
        var = row
    # print the value of var
    print(var)

In Python, empty strings are "falsey" while non-empty strings are "truthy". By using the statement if row: we would only proceed into the if statement when row contains non-empty strings, such as "On", or "Off".

Community
  • 1
  • 1
BenjaminGolder
  • 1,573
  • 5
  • 19
  • 37
0

A simple if/else will do

var = some_initial_value
for row in file:
     var = row[0] if row[0] else var
     print(var)
tdelaney
  • 73,364
  • 6
  • 83
  • 116