V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
oahebky
V2EX  ›  Python

[ Python ] 在 windows 系统下以 `"w"` 操作 `open` 非法(invalid)文件名的不同现象是为什么?

  •  
  •   oahebky · Aug 11, 2020 · 1935 views
    This topic created in 2088 days ago, the information mentioned may be changed or developed.
    fp = open("D:\\foo:bar.txt", "w")
    fp.close()
    

    上面 👆 这样的行为,执行不会报错,windows 系统中创建了一个 foo 文件名的文件


    fp = open("D:\\foo:bar:egg.txt", "w")
    fp.close()
    

    👆 这样的行为,执行就会报错,错误为:

    OSError: [Errno 22] Invalid argument: 'D:\\foo:bar:egg.txt'


    含有 ":" 字符的文件名在 windows 系统下是非法的( Invalid ),那么第一个 foo:bar.txt 也应该直接报错呀。

    这是为什么???

    2 replies    2020-08-11 09:50:17 +08:00
    lonewolfakela
        1
    lonewolfakela  
       Aug 11, 2020   ❤️ 8
    在文件名后面跟一个冒号是有特殊含义的,表示这个路径指向该文件的一个 ntfs alternate data streams (可以去搜搜这个名词)。
    具体到这里,你的第一个例子其实是创建了一个名字叫 foo 的文件,并为这个文件创建了一个名字叫 bar.txt 的 alternate data stream,并且之后如果你写入了内容的话,写入的内容都是会存到这个 alternate data stream 里去的。
    no1xsyzy
        2
    no1xsyzy  
       Aug 11, 2020   ❤️ 1
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4070 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 04:10 · PVG 12:10 · LAX 21:10 · JFK 00:10
    ♥ Do have faith in what you're doing.