Python文件名中的冒号 [英] Colon in file names in Python

查看:71
本文介绍了Python文件名中的冒号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,Windows 中的文件名不能包含冒号.但是,我遇到了一个问题,可以使用以下示例代码重现该问题:

As we all know, filenames in Windows can't contain colons. However, I ran into a problem, that can be reproduced with the following sample code:

import os
os.chdir('./temp')
names = ['a', 'b', 'word1: word2', 'c: file', 'd: file']

for name in names:
    with open(name, 'w') as f:
        f.write('foo')

此脚本在 ./temp 目录中创建三个文件:ab(带有 'foo')和 word1(空).它还会在 D:\ 中创建一个名为 file 的文件,该文件是可移动存储.它不会在C:\中创建任何内容,需要管理员权限才能写入;但是,它确实在当前工作目录中创建了一个文件.

This script creates three files in the ./temp directory: a, b (with 'foo') and word1 (empty). It also creates a file named file in D:\, which is removable storage. It doesn't create anything in C:\, which requires administrator rights to write in; however, it does create a file in the current working directory.

我不明白三件事:

  1. 为什么没有抛出任何异常(对于其他禁止字符,我得到 IOError)?
  2. 为什么 word1 文件是空的?
  3. 为什么要在当前工作目录中创建文件?

推荐答案

Windows NTFS 支持文件流".您基本上将数据附加到文件,在文件之外,并且无法正常查看.创建文件word1:word2"时,隐藏流word2"附加到word1".如果你把文件 word1 复制到另一台 NTFS 机器上,word2 数据会随你而来

Windows NTFS supports file "stream". You basically append data to a file, outside of the file, and can't be viewed normally. When you created the file "word1:word2", the hidden stream "word2" is attached to "word1". If you copied the file word1 to another NTFS machine, the word2 data would come with you

转到这里 http://technet.microsoft.com/en-us/sysinternals/bb897440.aspx 并下载流程序.运行它会告诉你 word2 是一个附加到 word1 的流

Go here http://technet.microsoft.com/en-us/sysinternals/bb897440.aspx and download the streams program. Running it will show you that word2 is a stream attached to word1

此页面还讨论了流:http://www.forensicfocus.com/dissecting-ntfs-hidden-streams

要真正轻松地证明这一点,您可以使用记事本,但需要使用 .txt 扩展名:

To really prove this easily, you can use Notepad but you need to use the .txt extension:

 file=open('word1.txt:word2.txt','w')
 file.write('Testing streams')
 file.close()

现在,使用 cmd 程序,将目录更改为您创建文件的位置.输入以下内容:

Now, using the cmd program, change directories to where you created the files. Type the following:

 c:\tmp> notepad word1.txt

您将看到一个空文件.现在,试试这个:

You will see an empty file. Now, try this:

 c:\tmp> notepad word1.txt:word2.txt

您应该看到文本Testing streams.

这篇关于Python文件名中的冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆