如果文件名或路径包含非字母和非下划线字符,如何在Python中导入?

6 投票
1 回答
8042 浏览
提问于 2025-04-16 11:12

我需要从一个文件中导入一个函数,这个文件所在的文件夹名字里有特殊字符,而且这个文件本身也有特殊字符。我不能更改这些名字来解决这个问题。在这种情况下,我该怎么导入呢?

1 个回答

7

是啊,这个命名真让人无语,不过这个方法应该能帮到你:

Instrument_Control = __import__("Instrument-Control.audio$pecial")
audiospecial = getattr(Instrument_Control, "audio$pecial")
print audiospecial
# <module 'Instrument-Control.audio$pecial' from 'Instrument-Control/audio$pecial/__init__.py'>
audiospecial.example_func()  # executes example_func() from audio$pecial

撰写回答