推荐学习书目
› 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
newton108
V2EX  ›  Python

如何确保 open('file', 'w') 创建的新文件在当前运行脚本所在的文件夹里?

  •  
  •   newton108 · Aug 11, 2012 · 3890 views
    This topic created in 5164 days ago, the information mentioned may be changed or developed.
    貌似所创建的文件是在系统的 pwd 里的,如果改成一个相对路径呢?
    6 replies  •  1970-01-01 08:00:00 +08:00
    jerry
        1
    jerry  
       Aug 11, 2012
    os.chdir(path)
    ufo22940268
        2
    ufo22940268  
       Aug 11, 2012
    那open('file', 'w')怎么使即将被打开的文件在是和当前python文件相同路径的呢?
    paloalto
        3
    paloalto  
       Aug 11, 2012
    我在web.py里是这么弄的:
    homedir = os.getcwd() #得到当前目录的路径
    filedir = '%s/static/upload/image' %homedir #图片存放路径
    d_path = filedir + '/%d/%d/%d' %(now.year, now.month, now.day)#按年月日创建分级目录

    fout = open(d_path + '/' + filename,'wb') #文件处理
    newton108
        4
    newton108  
    OP
       Aug 12, 2012
    @paloalto 可問題是,比如我 terminal 裡的 pwd 是 ~,如果 py 文件裡用 os.getcwd() 的話, 從 terminal 裡運行 py 文件得到的文件夾也是 ~,而不是 py文件所在的文件夾。
    newton108
        5
    newton108  
    OP
       Aug 12, 2012   ❤️ 2
    我自問自答吧
    os.path.dirname(__file__)
    leiz
        6
    leiz  
       Aug 12, 2012
    os.path.dirname(__file__)

    同楼上。。。
    没人用这个变量的么...?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2323 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 04:51 · PVG 12:51 · LAX 21:51 · JFK 00:51
    ♥ Do have faith in what you're doing.