V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
commoccoom
V2EX  ›  Python

Python 定义的函数无法打开文件?

  •  
  •   commoccoom · 2015-10-06 17:32:12 +08:00 · 3064 次点击
    这是一个创建于 3123 天前的主题,其中的信息可能已经有所发展或是发生改变。


    引用这个函数时无法打开 headers.json 文件 IOError: [Errno 2] No such file or directory: 'headers.json'
    第 1 条附言  ·  2015-10-06 18:32:47 +08:00
    当把主文件放在同一个目录时可以运行,放在另外一个文件夹就不能运行了
    第 2 条附言  ·  2015-10-06 19:36:24 +08:00
    使用了 f = open('./Get_HTML/headers.json') 好了,感谢各位
    7 条回复    2015-10-06 23:27:56 +08:00
    hahastudio
        1
    hahastudio  
       2015-10-06 18:35:25 +08:00
    这是当然啊,你指望 python 从哪个文件夹找文件啊= =
    放到另外一个文件夹,鬼知道是哪个文件夹= =
    commoccoom
        2
    commoccoom  
    OP
       2015-10-06 18:46:26 +08:00
    @hahastudio
    新建文件夹
    /Get_HTML
    headers.json
    get_html.py
    __init__.py
    test.py

    结构是这样的,运行 test.py 文件,调用 web_spider 函数,但是无法读取 headers.json 文件
    commoccoom
        3
    commoccoom  
    OP
       2015-10-06 18:49:07 +08:00
    csslayer
        4
    csslayer  
       2015-10-06 19:06:28 +08:00   ❤️ 1
    使用相对路径时是相对你执行脚本时的工作目录,和代码存放的位置没有关系。
    Kisesy
        5
    Kisesy  
       2015-10-06 19:15:56 +08:00   ❤️ 1
    你只要记住: python 执行的哪个文件,就得跟哪个在一块
    codeforlife
        6
    codeforlife  
       2015-10-06 19:24:10 +08:00   ❤️ 1
    f = open('./Get_HTML/headers.json')
    wizardforcel
        7
    wizardforcel  
       2015-10-06 23:27:56 +08:00 via Android
    headers.json 等价于 ./headers.json
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5440 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:00 · PVG 17:00 · LAX 02:00 · JFK 05:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.