推荐学习书目
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 · Oct 6, 2015 · 3882 views
    This topic created in 3904 days ago, the information mentioned may be changed or developed.


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

    结构是这样的,运行 test.py 文件,调用 web_spider 函数,但是无法读取 headers.json 文件
    commoccoom
        3
    commoccoom  
    OP
       Oct 6, 2015
    csslayer
        4
    csslayer  
       Oct 6, 2015   ❤️ 1
    使用相对路径时是相对你执行脚本时的工作目录,和代码存放的位置没有关系。
    Kisesy
        5
    Kisesy  
       Oct 6, 2015   ❤️ 1
    你只要记住: python 执行的哪个文件,就得跟哪个在一块
    codeforlife
        6
    codeforlife  
       Oct 6, 2015   ❤️ 1
    f = open('./Get_HTML/headers.json')
    wizardforcel
        7
    wizardforcel  
       Oct 6, 2015 via Android
    headers.json 等价于 ./headers.json
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1002 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 18:22 · PVG 02:22 · LAX 11:22 · JFK 14:22
    ♥ Do have faith in what you're doing.