Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This is probably quite a simple problem, but can't seem to figure it out or find any answered questions with regards to this issue.

xcombined=[]
for i in range (1,20):
    from 'files_'+str(i) import x
    for j in range(0,len(x)):
        xcombined.append(x[j])

results in the following error:

    import "files_"+str(i)
                  ^
SyntaxError: invalid syntax

I am wishing to import a list, (ie x=[15.34, ..., 15.54]) from files_1.py, files_2.py, etc and append it to another list called xcombined so that xcombined is sum of all of the "x's" from all the "files_*.py's". If I am correct 'files_'+str(i) cannot work as it isn't a string? Is there a quick way around this problem?

Thanks in advance. Paul

share|improve this question

2 Answers

From what I've understood, you're using .py files to store lists as python code.

This is extremely ineffective and will probably cause many problems. It's better to use simple text files (for exemple in the JSON format).

Still, here's how you should import modules with dynamically generated names:

import importlib
i = 1
myModule = importlib.import_module('files_'+str(i))
share|improve this answer

Use importlib module here, as import statement doesn't work with strings.

import importlib
xcombined=[]
for i in range (1,20):
    mod = importlib.import_module('files_'+str(i))
    x = mod.x  #fetech `x` from the imported module
    del mod    # now delete module, so this is equivalent to: `from mod import x`
    for j in range(0,len(x)):
        xcombined.append(x[j])
share|improve this answer
Does importlib exist on python 2.6 (this is the version my works linux box has). From running this, it doesn't? – Paul Wright 7 mins ago
@PaulWright try __import__('files_'+str(i)) on py2.6 – Ashwini Chaudhary 6 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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