0

I already know this will be (wrongly, in my opinion) labelled as duplicate because of this or this, which I've already looked at.

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. 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\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!

In the second link, the user wants to just open a file using 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?

Euler_Salter
  • 3,271
  • 8
  • 33
  • 74
  • https://stackoverflow.com/questions/9123517/how-do-you-import-a-file-in-python-with-spaces-in-the-name will help you. Please go through it – priya raj Jul 17 '17 at 10:13
  • @priyaraj I am not having problems with spaces in the file name – Euler_Salter Jul 17 '17 at 10:16
  • Have you tried something like this - https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7 – SuperShoot Jul 17 '17 at 10:22
  • @SuperShoot I better not do things like that because I have files with the same names, and I am not the only one using Spyder on this computer – Euler_Salter Jul 17 '17 at 10:25
  • Did you see this answer which doesn't permanently add to path variable if that is a concern to you - https://stackoverflow.com/a/3702243/6560549 – SuperShoot Jul 17 '17 at 10:29
  • 1
    path = r"C:\c:\\....\welcome.py" import path – priya raj Jul 17 '17 at 11:25

2 Answers2

1
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 *
Cary Shindell
  • 1,336
  • 8
  • 25
Surya
  • 84
  • 5
0

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.

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
Michael Schock
  • 575
  • 5
  • 8