I have two Python files. In my main file I work with a openpyxl module. In my second file I have many string lines with concatenating using Excel file cells, for example:
'/ip address=' + sheet['D'+ row].value + '\n'
and many others. But there is a problem, if I import that file to a main file using:
from file2 import *
I get many errors about undefined names like:
NameError: name 'sheet' is not defined
And it is really defined only in my main file, like:
wb = openpyxl.load_workbook(filename='clients.xlsx')
sheet = wb.get_sheet_by_name('Page1')
How can I import everything from my file2 and get it work?
As far as I can wrap my head around it, import only imports functions. execfile(*path*) should work for you in your case.
There are some more ways to import python into python, which you might want to check out.
Related
I know how to import functions from normal files...
but my file name is 'selection sort'
it contains a space in between
is there a way to import function from these without renaming it
I tried import selection sort and import selection_sort… both didn't work
I also watched few videos and questions like these but can't find the solution.
You can use the __import__() function like:
selection_sort = __import__("selection sort")
and then the file selection sort is imported as selection_sort.
While it is not recommended to have a space in the file name, you could try:
selection_sort = __import__("selection sort")
Sorry if the question is not well formulated, will reformulated if necessary.
I have a file with an array that I filled with data from an online json db, I imported this array to another file to use its data.
#file1
response = urlopen(url1)
a=[]
data = json.loads(response.read())
for i in range(len(data)):
a.append(data[i]['name'])
i+=1
#file2
from file1 import a
'''do something with "a"'''
Does importing the array means I'm filling the array each time I call it in file2?
If that is the case, what can I do to just keep the data from the array without "building" it each time I call it?
If you saved a to a file, then read a -- you will not need to rebuild a -- you can just open it. For example, here's one way to open a text file and get the text from the file:
# set a variable to be the open file
OpenFile = open(file_path, "r")
# set a variable to be everything read from the file, then you can act on that variable
file_guts = OpenFile.read()
From the Python docs on the Modules section - link - you can read:
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it
This means that importing a module has the same behavior as running it as a regular Python script, unless you use the __name__ as mentioned right after this quotation.
Also, if you think about it, you are opening something, reading from it, and then doing some operations. How can you be sure that the content you are now reading from is the same as the one you had read the first time?
I am working on a text editor made with python and i want to add a feature of Variable Explorer in my editor I am not able to extract the variable values from a python file. My basic working principle is that my program takes location of the current edited file and try to import it but I am not able to import because that is string not an object. It is bit confusing so let me show the code.
fileName='C:\Users\Project.py'
class varExplorer:
def ShowVarList(editfile):
editfile.replace('\','.')
editfile.replace('.py','')
editfile.replace(':','')
# so the file path will be like C.Users.Project
import editfile # the problem
print(editfile.__dict__)# here i will get dictionary of values
varExplorer.ShowVarList(fileName)
help taken for dict
print(editfile.__dict__)
from
I want to extract all the variable names with a python script, from a python file, without editing the python file
The main problem is that it cannot import from a string
import editfile # the problem
because it is a string and import does not take strings
So I want a function which can print all the variable and their values from a specific python file from any location.
Use importlib
import importlib
importlib.import_module(editfile)
Also be careful, str is immutable in Python, replace returns a new string and does not modify its argument.
So you get:
import importlib
class VarExplorer:
def show_var_list(editfile):
editfile = editfile.replace('\\','.')
editfile = editfile.replace('.py','')
editfile = editfile.replace(':','')
# so the file path will be like C.Users.Project
module = importlib.import_module(editfile) # the solution
print(vars(module))
I wish to be able to import a file in Python whose source is a text file that will be often modified.
In other words, let's suppose that I have a file name, dados.py whose content in a given moment is:
x=[2, 3, 7, 9]
(and this is the only line of the file (possible?))
and my main program has the line
import dados
What I want is that when the import is made I will have an array with the values seen above.
But, if the values of the file dados.py change, the next time that the main program runs it will work with the new values.
The thing is that I don't know if I can have a line of code with variables and if python will recognize that it must execute this line.
The question I am trying to explain in details is because I had a working program with the x=[2, 3, 7, 9] writen on the source code. The moment that I replaced that line by:
import dados
line, python complains with a message like
File "testinclude.py", line 15, in <module>
print(x)
NameError: name 'x' is not defined
Your variable is defined within a module, so you must namespace the variable
import dados
print(dados.x)
Or you can import x from dados
Alternative solution would be to use some JSON or other configuration file, then read and load it. It's not clear why you need a Python file only to define variables
In this instance it is probably better to use a file instead of a python module. However, if you insist on using a module, you can store the data in a variable and access it using the "." operator.
I was taking a look at some commit of a project, and I see the following change in a file:
- import dataFile
+ dataFile = __import__(dataFile)
The coder replaced import dataFile by dataFile = __import__(dataFile).
What exactly is the difference between them?
import dataFile
translates roughly to
dataFile = __import__('dataFile')
Apparently the developer decided that they wanted to use strings to identify the modules they wanted to import. This is presumably so they could dynamically change what module they wanted to import ...