0

I know that the question that i posted has been answered before but i tried to use the posted answers it didn't work well in my case. The problem is that I'm trying to store multiple entries from a while loop into a variable and I'm trying to access this variable outside this loop. The output is only the first line as if the loop is not iterating throw the entire file. Here is the code that I wrote

import csv

keyword = None

with open('test.csv', 'rb') as f:
      reader = csv.reader(f, delimiter='\t')
      headers = reader.next()
      for row in reader:
           keywords = (row[0].strip())

print (keywords) 

The test file has the following structure :

symbol
code_id_164751
code_id_313270
code_id_96306
code_id_494305
code_id_468128
code_id_303451
code_id_274562

The output of the code just give me just the first code_id:

code_id_164751

The desired output is the entire list. Even that I declared the variable keywords before the while loop it seems that I could not get it outside the loop (this is what was suggested in the other questions that I saw)

5
  • 1
    As a start, you need to pluralise keyword Commented Mar 14, 2016 at 14:04
  • 1
    You appear to be reassigning keywords at each iteration. Commented Mar 14, 2016 at 14:04
  • You replace the value of Keywords around every iteration of the loop. Commented Mar 14, 2016 at 14:04
  • You can get it outside the loop, but keywords is being redefined at each iteration. If it were to build up into a list, it would be a list within your loop as well. Is that really what you want? Commented Mar 14, 2016 at 14:05
  • I tried to write it as a list I couldn't get it outside the loop too Commented Mar 14, 2016 at 14:06

3 Answers 3

3

This has nothing to do with defining the variable inside or outside the loop. You define keyword as a single variable, and re-assign it every time through the loop, so naturally it's only going to get the last value.

Instead you should define it as a list and append your value each time:

keywords = []

...
        keywords.append(row[0].strip())
Sign up to request clarification or add additional context in comments.

3 Comments

You need to pluralise keyword
@Mondher: Change keyword = [] to keywords = []
Thank you I just realised this looking again throw the code.
0

You need

keywords.append(row[0].strip())

Comments

0

Please try to append result to old result. Because in your code you just assign
keywords = (row[0].strip()) so it replace old keyword.

so change keywords = (row[0].strip()) to keywords += (row[0].strip())

2 Comments

Thatprobablywon'tdowhattheOPwants.
Ya but here at this line they also append result to list or append it to simple string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.