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
newton108
V2EX  ›  Python

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

  •  
  •   newton108 · 2012-08-11 08:05:36 +08:00 · 2979 次点击
    这是一个创建于 4248 天前的主题,其中的信息可能已经有所发展或是发生改变。
    貌似所创建的文件是在系统的 pwd 里的,如果改成一个相对路径呢?
    6 条回复    1970-01-01 08:00:00 +08:00
    jerry
        1
    jerry  
       2012-08-11 08:23:56 +08:00
    os.chdir(path)
    ufo22940268
        2
    ufo22940268  
       2012-08-11 08:44:29 +08:00
    那open('file', 'w')怎么使即将被打开的文件在是和当前python文件相同路径的呢?
    paloalto
        3
    paloalto  
       2012-08-11 08:46:04 +08:00
    我在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
       2012-08-12 06:30:03 +08:00
    @paloalto 可問題是,比如我 terminal 裡的 pwd 是 ~,如果 py 文件裡用 os.getcwd() 的話, 從 terminal 裡運行 py 文件得到的文件夾也是 ~,而不是 py文件所在的文件夾。
    newton108
        5
    newton108  
    OP
       2012-08-12 06:32:37 +08:00   ❤️ 2
    我自問自答吧
    os.path.dirname(__file__)
    leiz
        6
    leiz  
       2012-08-12 10:27:37 +08:00
    os.path.dirname(__file__)

    同楼上。。。
    没人用这个变量的么...?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5946 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:07 · PVG 10:07 · LAX 19:07 · JFK 22:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.