Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you import a file in python with spaces in the name?

Do I have to take out all the spaces in the file name to import it, or is there some way of telling import that there are spaces?

like image 957
lilfrost Avatar asked Feb 03 '12 04:02

lilfrost


People also ask

Can you put spaces in file names?

Don't start or end your filename with a space, period, hyphen, or underline. Keep your filenames to a reasonable length and be sure they are under 31 characters. Most operating systems are case sensitive; always use lowercase. Avoid using spaces and underscores; use a hyphen instead.

How do you name a space in Python?

Spaces are not allowed in variable names, so we use underscores instead of spaces. For example, use student_name instead of "student name". You cannot use Python keywords as variable names. Variable names should be descriptive, without being too long.

How do I import a file into Python?

You need to tell python to first import that module in your code so that you can use it. If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory.

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.


1 Answers

You should take the spaces out of the filename. Because the filename is used as the identifier for imported modules (i.e. foo.py will be imported as foo) and Python identifiers can't have spaces, this isn't supported by the import statement.

If you really need to do this for some reason, you can use the __import__ function:

foo_bar = __import__("foo bar") 

This will import foo bar.py as foo_bar. This behaves a little bit different than the import statement and you should avoid it.

like image 128
Jeremy Avatar answered Oct 05 '22 17:10

Jeremy