How would I get the elements iterated by a for loop to a list where I can print them out later in the my code? For example:
for fname in dirlist:
if fname.endswith(('.tgz','.tar')):
print fname
fname only shows all the elements from dirlist only in the loop. I would like to view the elements at other areas in my code. I tried li = fname ... but only one element shows up, when in fact there are about 7 elements. Thanks!
You can use a list comprehension:
tarfiles = [fname for fname in dirlist if fname.endswith(('.tgz','.tar'))]
to print the filenames, use
print "\n".join(tarfiles)
or
for fname in tarfiles:
print fname
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With