【发布时间】:2017-02-28 15:19:01
【问题描述】:
我有一个包含文本预处理功能的脚本“preprocessing.py”:
def preprocess():
#...some code here
with open('stopwords.txt') as sw:
for line in sw.readlines():
stop_words.add(something)
#...some more code than doesn't matter
return stop_words
现在我想在另一个 Python 脚本中使用这个函数。 所以,我做了以下事情:
import sys
sys.path.insert(0, '/path/to/first/script')
from preprocessing import preprocess
x = preprocess(my_text)
最后,我解决了这个问题:
IOError: [Errno 2] No such file or directory: 'stopwords.txt'
问题肯定是“stopwords.txt”文件位于第一个脚本旁边,而不是第二个。
有没有办法指定这个文件的路径,而不是对脚本'preprocessing.py'做任何改变?
谢谢。
【问题讨论】:
-
在这里尝试使用完整的限定路径:
with open('stopwords.txt') as sw: -
不要依赖
preprocess中的当前工作目录。使用os.path.dirname(os.path.realpath(__file__))获取目录并使用该目录查找stopwords.txt。 -
我在这里看到两个问题:1- 问:如何导入不属于同一个Python项目(包)的Python模块? A: 把它放在 pythonpath 中——首选的方法是安装它(create a simple
setup.py(或使用cookiecutter包),运行pip install -e .)。sys.path.insert()应避免使用/不使用硬编码路径¶ 2- Q: 如何访问与代码相关的资源(文件)。 答:pkgutil.get_data(),pkg_resources, appdirs
标签: python python-2.7