Python Windows 10 Import from Different Directory - python

I'm trying to import the file File.py file from a specific directory, C:\MyPythonFiles. This is what I tried(among several other different attempts):
import sys
sys.path.append("c:\MyPythonFiles")
import File.py
Can someone please tell me how to import File.py from the diretory C:\MyPythonFiles ?
Removing the .py so that its 'import File' didn't work either:
[UPDATE]
So in my File.py, I had an import for a file that I did not include in c:\MyPythonFiles, so that was a huge problem.
I edited File.py so it only has one function, printHello(). The script works, but PyCharm still does not recognize 'File' for import. I can still use the line File.printHello(), but it's annoying since PyCharm is not autofilling the functions for 'import File'. Any ideas on how to solve this new problem?
[UPDATE]
I think #alex answered the original question, and my PyCharm issue should be a seperate question. Thanks for the help #alex!

import sys
sys.path.append("c:\\MyPythonFiles")
import File
or
import sys
sys.path.append(r"c:\MyPythonFiles")
import File
or
import sys
sys.path.append("c:/MyPythonFiles")
import File
1.Don't need ".py"
2.path link error
Windows path in Python

Related

Python imports from the same folder doesn't work

I created a working folder: C:\Users\robin\bayesian-optim
Inside there are module1_test.py and work.py
I have some functions in module1_test.py that I want to use in work.py, but using import module1_test as mmm in the shell gives the following error :
ImportError: No module named 'dossier_module'
It is the first thing that I do not understand. To go further,
I tried this :
import sys
sys.path.insert(0,'C:/Users/robin/bayesian-optim')
Then it worked, but my real goal is to clone some git codes in this folder and to call them instead of my example module1_test.py. When I do so, cloning "pymoo" in C:\Users\robin\bayesian-optim, I have the same problem :
File "C:/Users/robin/bayesian-optim\pymoo\pymoo\__init__.py", line 1, in <module>
from pymoo.version import __version__
ImportError: No module named 'pymoo.version'
All the .py folders inside of the cloned repo are not foundable, and it would mean that I would have to add at the beginning of every code "import sys, sys.path.insert(0, path/to/this/folder)". Can somebody help me ?

how to import modules from local repository with virtualenv and pip

I have a question that I assume has a simple answer, but for some reason I am struggling to find it on my own. I have created and activated a virtual environment with virtualenv, and I am trying to install all the necessary packages in order to create a requirements.txt file.
I have, for example, a Python file that begins like this:
import xml.etree.ElementTree as ET
from lib.project import Projector
from lib import writer
import os
import datetime
from datetime import timedelta
from datetime import datetime
import pprint
When I try to run this file from the virtual machine, I receive the following error:
Traceback (most recent call last):
File "readMap.py", line 2, in <module>
from lib.project import Projector
ModuleNotFoundError: No module named 'lib.project'
My problem is that I'm not sure why the virtual environment can't find project.py. My directory structure is:
regiaoSul
lib
__init__.py
arrival_conversion.py
coord_conversion.py
message_conversion.py
project.py
route_conversion.py
stop_conversion.py
wkt_parser.py
writer.py
readMap.py
json_generator.py
The import on line 2 implies lib is a module rather than "a simple repository".
I will try running the script with the flag -m. Something like this -
python -m script_name
make sure to drop the .py extension when you run with -m flag.
Another advice: you don't need to install python files to the virtual environment, they are not some external libraries. They only need to be present (with the same order of packaging) when you run your script.
Thanks to everyone who responded. I believe the issue was some sort of dependency problem. In readMap.py I had imported writer from lib, and in writer.py I had imported Projector from project. I moved the function that required Projector from writer.py to readMap.py and it worked.
I still don't fully understand why this was a problem. Until recently I had been running my scripts in PyCharm and they all worked with the structure I had. It was only when I tried to run them from the command line in my virtual machine that they didn't work.
If anybody would like to explain the distinction to me and what the exact problem was with my imports, feel free to.
I sometimes face the same issue. A solution is to add the path to sys.path by:
import sys
sys.path.insert(0, "/path/to/your/package_or_module")

How do I import a module into my file in VS code while both of them are in the same folder?

I have two files, math_functions.py, and test.py under the same folder. I want to import math_functions into test.py but for some reason when I simply type it like below it won't work. I also tried 'Import Example3.math_functions' or when the Example3 folder had a space like so 'import Example_3.math_functions' it still throws an error. I forgot to show the error message but vs code tells me this 'import "math_functions" could not be resolved'. How can I import math_functions? I am running python 3.8
Try import the class or method directly
from math_functions import my_math_function
or if you want to import all of them at once, try
from math_functions import *
Okay so from what I found out, the code will still actually run and let you import the module regardless, I think this is just a visual studio thing throwing an error like this but this will still work regardless, now im curious as to whether there is anyway to get rid or ignore the error message. Thank you to those who have looked into it and tried to help
To import a file in the same folder, #shiny is right:
from math_functions import *
Referece: packages
About the warning that has no effect on code execution but wave underline displayed, if you're using pylint, you can add the following settings to your user settings.json file (opened with the File > Preferences > Settings command Ctrl+,):
"python.languageServer": "Jedi",
"python.linting.pylintArgs": ["--disable=W,C"],
Other Linter settings and detailed information you can refer to: linting-python-in-vscode.

How to import my python file in another file in visual studio code

I am using python/selenium in visual studio code. I am trying to import my another python class driverScript which resides in executionEngine module and in the file DriverScript. I have imported as below:
import driverScript from executionEngine.DriverScript
It is producing error:
Traceback (most recent call last):
File "c:/Selenium/Selenium-Python Framework/RK_Practice/Tests/mainTest.py", line 5, in <module>
from executionEngine.DriverScript import driverScript
ModuleNotFoundError: No module named 'executionEngine'
How can I import correctly? Your help is very much appreciated.
If the script you are wishing to import is not in the current directory, you may want to take this approach:
import sys
sys.path.insert(1, '/path/to/script/folder')
import driverScript from executionEngine.DriverScript
If your python file is on the same level in dir, then you can import just by calling:
import filename
If your python file is inside another folder, then you need to create a blank __init__.py file that will help python to understand it's a package. Then you can import that as follows:
from folderName import filename
Depends on where executionEngine is supposed to come from. If it's from a package installable via a package manager such as pip or Anaconda, looks like it's not properly installed. If you installed it yourself, you probably need to add the directory containing executionEngine to your PYTHONPATH, so the Python interpreter can find it. This can be done in the VSCode environment files. See the PYTHONPATH section in https://code.visualstudio.com/docs/python/environments

how to make a file act as a python module

I want to make a file that is consisted of 3 python programs.
but, when I want to access one of the there files from one of them, it cant find the folder.
I made a init python file in it so python can recognize it as a module
my folder struct:
dlgo/
__init__.py
goboard_slow.py
gotypes.py
my goboard_slow:
from dlgo.gotypes import player
error:
Traceback (most recent call last):
File "C:\Users\asus\Desktop\dlgo\goboard_slow.py", line 2, in <module>
from dlgo.gotypes import player
ImportError: No module named 'dlgo'
Access as below:
from dlgo.gotypes import players
See here more info on "Guido's decision" on imports in python 3 and complete example on how to import in python 3.
maybe try from (filename) import (functionname)
Tl;dr:
from gotypes.py import player
when you specify path to a file, interpreter starts looking for it inside same folder, unless you give it path from main dirrectory like '/' or 'C:\'
You can import a py file with the following statement:
# Other import
import os
import sys
if './dlgo' not in sys.path:
sys.path.insert(0, './dlgo')
from dlgo.gotypes import player
NOTE:
For IDE like PyCharm, you can specify the import path using the Project Structure setting tab (CTRL+ALT+S)
Helpful stack overflow questions [maybe off topic]:
What is the right way to create project structure in pycharm?
Manage import with PyCharm documentation:
https://www.jetbrains.com/help/pycharm/configuring-project-structure.html

Categories

Resources