In python I'm having an issue with running some code, but only when it's part of a list comprehension.
The following code works:
from os import listdir
from os.path import isfile, join
IMPORT_DIR = '/media/import_files/'
files = listdir(IMPORT_DIR)
FILES_FOR_IMPORT = []
for f in files:
if isfile(join(IMPORT_DIR, f)):
FILES_FOR_IMPORT.append(f)
However, the following (supposedly equivalent) list comprehension throws an error:
FILES_FOR_IMPORT = [ f for f in listdir(IMPORT_DIR) if isfile(join(IMPORT_DIR,f)) ]
Stack trace:
File "/home/mitch/workspace/mysite/flat_file_importer/ImporterMain.py", line 12, in <module>
class ImporterMain():
File "/home/mitch/workspace/mysite/flat_file_importer/ImporterMain.py", line 25, in ImporterMain
FILES_FOR_IMPORT = [ f for f in listdir(IMPORT_DIR) if isfile(join(IMPORT_DIR,f)) ]
File "/home/mitch/workspace/mysite/flat_file_importer/ImporterMain.py", line 25, in <listcomp>
FILES_FOR_IMPORT = [ f for f in listdir(IMPORT_DIR) if isfile(join(IMPORT_DIR,f)) ]
NameError: name 'IMPORT_DIR' is not defined
In testing, I have the first bit before the second bit; both are getting executed. The first works, the second does not. Same behavior if I only execute one at a time - one works, one does not.
Clearly the IMPORT_DIR
variable is defined - it is being used in the first bit of code, so I'm not sure why Python is spitting this error at me.
The list comp, which I've used before, is stolen from here: https://stackoverflow.com/a/3207973/3665278
The full code (with the bit that is working first and the list comp second):
from os import listdir
from os.path import isfile, join
import re
class ImporterMain():
IMPORT_DIR = '/media/import_files/'
files = listdir(IMPORT_DIR)
FILES_FOR_IMPORT = []
for f in files:
if isfile(join(IMPORT_DIR, f)):
FILES_FOR_IMPORT.append(f)
FILES_FOR_IMPORT = [ f for f in listdir(IMPORT_DIR) if isfile(join(IMPORT_DIR,f)) ]