473,385 Members | 1,338 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

importing files from a directory

I'm a total Python newbie, so bear with me here...

I'm writing a program that has a user-configurable, module-based
architecture. it's got a directory where modules are stored (.py files)
which subclass one of several master classes.

My plan is to have the program go into the folder called "Modules" and
load up each file, run the code, and get the class and append it to an
array so I can work with all of the objects later (when I need to
actually use them and whatnot).

What I'm currently doing is:

import os

print "Loading modules..."
mod_dir = "Modules"

module_list = [] #empty list...

dir_list = os.listdir(mod_dir)

for item in dir_list:
# strip off the extensions...
if (item == "__init__.py"):
continue
elif (item[-3:] == '.py'):
mod_name = item[:-3]
elif (item[-4:] == '.pyc'):
mod_name = item[:-4]
else:
continue

print "Loading %s..." % mod

module_list.append(__import__("Modules.%s" % mod))

print "Done."
it works more or less like I expect, except that...

A. the first time it runs, blah.py then has a blah.pyc counterpart.
When I run the program again, it imports it twice. Not horrible, but
not what I want. is there any way around this?

B. module_list winds up consisting of items called 'Modules.blah' and
I'd like to have just blah. I realize I could say:

my_module = __import__("Modules.%s" % mod)
module_list.append(getattr(my_module, mod))

but...

is there a better way to accomplish what I'm trying to do?

tia.

....spike

Jul 21 '05 #1
2 1336
Am Sat, 09 Jul 2005 20:30:04 -0700 schrieb spike grobstein:
I'm a total Python newbie, so bear with me here...

I'm writing a program that has a user-configurable, module-based
architecture. it's got a directory where modules are stored (.py files)
which subclass one of several master classes. [cut]
for item in dir_list:
# strip off the extensions...
if (item == "__init__.py"):
continue
elif (item[-3:] == '.py'):
item.endswith(".py") would be more python-like.
mod_name = item[:-3]
elif (item[-4:] == '.pyc'):
elif item.endswith(".pyc"):
continue # Don't load module twice
else:
continue

print "Loading %s..." % mod

module_list.append(__import__("Modules.%s" % mod))

print "Done."
it works more or less like I expect, except that...

A. the first time it runs, blah.py then has a blah.pyc counterpart.
When I run the program again, it imports it twice. Not horrible, but
not what I want. is there any way around this?
See above: Just don't load it. The compiled "pyc" file is taken
automatically if it is newer than the "py" file.
B. module_list winds up consisting of items called 'Modules.blah' and
I'd like to have just blah. I realize I could say:

my_module = __import__("Modules.%s" % mod)
module_list.append(getattr(my_module, mod))


I use this getattr() after __import__, too. I don't think there
is a easier way.

HTH,
Thomas
--
Thomas Güttler, http://www.thomas-guettler.de/
Jul 21 '05 #2
my reason for loading both the .py and .pyc files was just in case
compiled files were supplied as modules... but I'm gonna disallow that,
so yeah.

I also got a response in email and I've been dabbling with my code
since I posted this and found a slightly better way of handling this
plugin system...

I stuck the import code into the Modules/__init__.py file, so it can
act as a kind of manager (instead of moving the files to a
Modules(disabled) directory) and appended the __import__s to an array.

like this:

spike@flaphead ~/Aphex $ cat Modules/__init__.py
module_list = []

def load_module(mod_name):
mod = __import__("Modules.%s" % mod_name)
mod = getattr(mod, mod_name)
module_list.append(mod.module())

def load_modules():
load_module("nes")
load_module("snes")
load_module("mame")

load_modules()

[end code]

I then just have to 'import Modules' from my main program and the whole
module import thing is encapsulated and invisible to my main program.

I'm gonna add some functions to the Modules module to make fetching
plugins a little less ambiguous (get_module(index) and
get_named_module(module_name), etc).

Thanks for the help. Python's making me have to think a little
backwards. I have to make sure I declare my functions before I call
them, but it's a very cool language overall.

....spike

Jul 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Charles Krug | last post by:
List: I'm trying to use the example files from Programming Python, 2nd Ed. I've copied them into c:\Python24\Examples\PP2E. Launching any of the examples programs by themselves seems to work...
3
by: Elmo Watson | last post by:
I've been asked to develop a semi-automated type situation where we have a database table (sql server) and periodically, there will be a comma delimited file from which we need to import the data,...
2
by: Debbie CD UK | last post by:
I have a large amount of log files from an electronic contro tester that I need to import in to an Access database Unfortunately, they are not comma delimited or fixed with but different fields...
29
by: Natan | last post by:
When you create and aspx page, this is generated by default: using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.Text; using...
1
by: Toby | last post by:
Hi, I've managed to get my hands on the ms 2003 toolkit, and have successfully (i think) created a .pyd file in win xp (setup.py is provided intersystems cache): ...
7
by: hg | last post by:
Hi, I have the following problem. I find in a directory hierarchy some files following a certain sets of rules: ..../.../../plugin/name1/name1.py ..... ..../.../../plugin/namen/namen.py
12
by: JMO | last post by:
I can import a csv file with no problem. I can also add columns to the datagrid upon import. I want to be able to start importing at the 3rd row. This will pick up the headers necessary for the...
1
by: thadson | last post by:
Hi, I'm trying to import specific cells from MS Excel 2000 spreadsheets to MS Access 2000 tables then move the spreadsheets to a different directory. I'm very new to this and I'm having trouble...
3
by: Chanman | last post by:
This is probably a simple question to most of you, but here goes. I've downloaded the xlrd (version 0.6.1) module and placed in in the site-packages folder. Now, when I write a script, I type: ...
1
by: aconti74 | last post by:
Hello I am new to vba programming/coding. I am writing a program that goes through a directory of text files and imports them into the database. The problem is eventually the database gets to big...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.