简体   繁体   中英

How to import module from one python file to another python file?

I am new to python. I am confused with importing in python and I am using two python files.

re1.py:

import datetime

import re2

re2.py:

print datetime.datetime.now()

When I run the re1.py file, it gave the error,

print datetime.datetime.now()
NameError: name 'datetime' is not defined

What is the best way to solve this error ?

When you import datetime in re1.py , you import it in the scope of only the re1.py file, and not in re2.py . In other words, if you import something in one module, it won't cross over onto the other.

To fix this, you must import datetime in re2.py (and you don't necessarily need it in re1.py )

your code should be:
re1.py:

import datetime  
import re2

re2.py:

import datetime  
print datetime.datetime.now()  

import re2 doesn't means simply replace the statement with another file:

import datetime  
# re2.py  
import datetime  
print datetime.datetime.now()  

you have to make sure all the modules you import are working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM