[英]python: import module from different file directory, with folder names having spaces
I already know this will be (wrongly, in my opinion) labelled as duplicate because of this or this , which I've already looked at. 我已经知道,由于这个或this ,这(错误地,我认为)将被标记为重复,这是我已经研究过的。
However my problem is different, and cannot be solved with the answers found there. 但是,我的问题有所不同,无法用在那里找到的答案解决。
So I have a python script in C:\\Users\\Me\\Desktop\\My folders\\Projects\\My stuff\\Last Folder\\some_file.py
. 所以我在
C:\\Users\\Me\\Desktop\\My folders\\Projects\\My stuff\\Last Folder\\some_file.py
有一个python脚本。 From this I want to import a file in the same directory, ie inside Last Folder
, for this I just use import file
. 从这个我想导入同一目录中的文件,即在
Last Folder
,为此,我只使用import file
。 However, then I have a file in C:\\Users\\Me\\Desktop\\My Other Folder\\My Other Projects\\ My Other Stuff\\other_file.py
. 但是,然后我在
C:\\Users\\Me\\Desktop\\My Other Folder\\My Other Projects\\ My Other Stuff\\other_file.py
有一个文件。 As you can see the folders have spaces. 如您所见,文件夹中有空格。
Now in the second of the two links above we are told how to import a python file with spaces in the name, a python file, not a folder! 现在,在上面两个链接的第二个中,我们被告知如何导入名称中带有空格的python文件,python文件而不是文件夹!
In the second link, the user wants to just open a file using os. 在第二个链接中,用户只想使用os打开文件。
I instead want to import it. 我想导入它。 How do I do it?
我该怎么做? When I try
当我尝试
import Users.Me.Desktop.My Other Folder.My Other Projects.My Other Stuff.other_file.py
it says "invalid syntax" because of the spaces. 由于空格,它说“语法无效”。 How can I solve this?
我该如何解决?
import sys
sys.path.append('\Users\Me\Desktop\My folders\Projects\My stuff\Last Folder\some_file.py.')
# From this I want to import a file in the same directory, i.e. inside Last Folder, for this I just use import file. However, then I have a file in C:\Users\Me\Desktop\My Other Folder\My Other Projects\ My Other Stuff
from other_file import *
I needed to import a utils.py
file into a Google Colab Notebook and this worked for me, combining the solution from Surya and here . 我需要将
utils.py
文件导入Google Colab Notebook,这对我来说很有效,将Surya和此处的解决方案结合在一起。
from google.colab import drive
drive.mount('/content/drive')
import sys
sys.path.append("/content/drive/My Drive/Colab Notebooks") # note the absolute path
print(sys.path)
from utils import a, b, c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.