1

Is there a way to extend an array that stores data from a file on each iteration of a for-loop and with command combo, using glob. Currently, I have something like

import glob
from myfnc import func


for filename in glob.glob('*.dta'):
    with open(filename,'rb') as thefile:

        fileHead, data = func(thefile)

where func is defined in another script myfnc. What this does is on each iteration in the directory, stores the data from each file in fileHead and data (as arrays), erasing whatever was there on the previous iteration. What I need is something that will extend each array on each pass. Is there a nice way to do this? It doesn't need to be a for-loop, with combo. That is just how I am reading in all files from the directory.

I thought of initializing the arrays beforehand and then try extending them after the with is done on one pass, but it was giving me some kind of error with the extend command. With the error, the code would look like

import glob
from myfnc import func

fileHead, data = [0]*2


for filename in glob.glob('*.dta'):
    with open(filename,'rb') as thefile:

        fileHeadExtend, dataExtend = func(thefile)

    fileHead.extend(fileHeadExtend)
    data.extend(dataExtend)

So, the issue that it has is fileHead and data are both initialized but as int's. However, I don't want want to initialize the arrays to so many zeros. There should not be any arbitrary values in there to begin with. So, that is where issue is lying for this.

9
  • 1
    Add the Python error message to your question.
    – user3657941
    Commented May 26, 2016 at 18:17
  • AttributeError: 'int' object has no attribute 'extend'
    – Lou
    Commented May 26, 2016 at 18:28
  • Now you need to figure out which variable is an int.
    – user3657941
    Commented May 26, 2016 at 18:39
  • Post the entire error message in the question, add the traceback as well! Commented May 26, 2016 at 19:14
  • although it seems a bit obvious... fileHead, data = [0]*2 sets both fileHead and data to the integer 0 and then you try to extend both of them... they are both 0, how are you extending 0?!? Commented May 26, 2016 at 19:15

1 Answer 1

0

You want:

import glob
from myfnc import func

fileHead = list()
data = list()

for filename in glob.glob('*.dta'):
    with open(filename,'rb') as thefile:
        fileHeadExtend, dataExtend = func(thefile)
    fileHead.extend(fileHeadExtend)
    data.extend(dataExtend)
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.