在python中如何导入两个不同目录下自定义的模块呢

Python021

在python中如何导入两个不同目录下自定义的模块呢,第1张

import sys

print sys.path

上面的代码会给出所有可用的python路径,你把.py文件放到这些路径下面就可以在其他文件里导入它了。

另外一个特殊的路径就是当前路径,比如你在一个文件夹test下新建两个.py文件,分别为123.py 和456.py ,那么你可以在123.py写:

import 456

就可以导入456.py了。

python的模块都是.py文件,提示invaild syntax 是说语法错误。如果你用的是python3,那你的print就写错了。python2和3的print 区别如下。

print 'hello world' #python2

print('hello world') #python3

I have a very wierd problem. When i run the file from a different directory it runs fine. but other wise i get this error

from textprocessor import *

File "/home/mohit/Documents/analysis/categorization/textprocessor.py", line 2, in <module>

import nltk

File "/usr/local/lib/python2.7/dist-packages/nltk/__init__.py", line 101, in <module>

import ccg

File "/usr/local/lib/python2.7/dist-packages/nltk/ccg/__init__.py", line 15, in <module>

from chart import *

File "/usr/local/lib/python2.7/dist-packages/nltk/ccg/chart.py", line 33, in <module>

from nltk.parse.api import *

File "/usr/local/lib/python2.7/dist-packages/nltk/parse/__init__.py", line 46, in <module>

from featurechart import *

File "/usr/local/lib/python2.7/dist-packages/nltk/parse/featurechart.py", line 24, in <module>

import nltk.data

File "/usr/local/lib/python2.7/dist-packages/nltk/data.py", line 41, in <module>

import zipfile

File "/usr/lib/python2.7/zipfile.py", line 460, in <module>

class ZipExtFile(io.BufferedIOBase):

AttributeError: 'module' object has no attribute 'BufferedIOBase'

I am tryin to import nltk module

You've called a script in the same directory "io.py", and this is interfering with the io module in the stdlib. Rename it.

You must have a script in your folder named nltk.py, io.py, zipfile.py, or some such. When you run the file in the same directory, it is imported instead of the appropriate python or nltk module.

Where is nltk? Is it pure Python code? You may want to put that in site-wide modules folder or in your cwd.