简体   繁体   中英

Accessing a variable outside a loop Python

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)

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())

你需要

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

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM