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

Python3 创建目录,加不加 '.' 表示相对目录起点,有区别吗?

  •  1
     
  •   miniyao · 2018-01-08 13:58:14 +08:00 · 2235 次点击
    这是一个创建于 2271 天前的主题,其中的信息可能已经有所发展或是发生改变。
    os.mkdir('./my-project/scripts/') 或者用 os.mkdir(os.path.join('.', 'my-project', 'scripts')) 这两种写法,加不加 '.' 都可以执行。

    主要用 Py3,加 '.' 和 不加 '.' 表示相对目录起点,有什么区别吗?(印象里 Py2 版本,以前看到有人说不加 '.' 在某些系统上会 OSError?)
    6 条回复    2018-01-09 21:57:37 +08:00
    ysc3839
        1
    ysc3839  
       2018-01-08 15:13:10 +08:00 via Android
    我猜测要看操作系统怎么处理。
    est
        2
    est  
       2018-01-08 15:23:34 +08:00
    跟 python 和 3 和创建 和目录都没关系。跟操作系统文件系统 syscall 有关系。
    flniu
        3
    flniu  
       2018-01-08 22:28:56 +08:00
    “都可以执行”。。。
    一个语句只要没有语法错误,就可以执行,能说明什么?
    flniu
        4
    flniu  
       2018-01-08 22:32:11 +08:00
    >>> import os
    >>> os.path.join('.', 'my-project', 'scripts')
    './my-project/scripts'
    >>> os.path.join('my-project', 'scripts')
    'my-project/scripts'

    './my-project/scripts' 和 'my-project/scripts' 倒是等价。
    './my-project/scripts' 和 '/my-project/scripts' 意思差远了去了。

    建议楼主温习 Linux 基础知识。从前流行《鸟哥的 Linux 私房菜》,不知道现在流行的 Linux 入门书是什么。
    miniyao
        5
    miniyao  
    OP
       2018-01-09 09:18:38 +08:00 via iPhone
    @flniu 谢谢,解释一下,我说 os.mkdir('./my-project/scripts/') 加不加 '.' 都可以执行的意思,这里是指加不加 './'。

    '/path' 斜杠打头,没理解错的话,是指绝对根目录吧
    thautwarm
        6
    thautwarm  
       2018-01-09 21:57:37 +08:00
    windows 按 package 路径优先搜索,而 linux 会优先搜索当前目录。
    windows 上,你使用`some_script.py filename`时,这个`filename`不按照`./`开头,就会优先查 python 目录的 scripts/底下的`filename`。
    linux 下的,见 4L 的说法。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5648 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 01:43 · PVG 09:43 · LAX 18:43 · JFK 21:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.