【发布时间】:2016-03-09 22:51:21
【问题描述】:
试试:
import os, shutil
wd = os.path.abspath(os.path.curdir)
newfile = os.path.join(wd, 'testfile')
print str(newfile)
with open(newfile, 'w') as f: f.write('Hello bugs')
shutil.move(newfile, os.path.join(wd, 'testfile:.txt')) # note the :
现在检查目录 - 新文件被删除并且没有其他文件被创建 - 进程以退出代码 0 结束。
如果你发出:
shutil.move(newfile, os.path.join(wd, 'testfile:')) # note no extension
它吹了:
Traceback (most recent call last):
File "C:/Users/MrD/.PyCharm40/config/scratches/scratch_3", line 9, in <module>
shutil.move(newfile, os.path.join(wd, 'testfile:'))
File "C:\_\Python27\lib\shutil.py", line 302, in move
copy2(src, real_dst)
File "C:\_\Python27\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\_\Python27\lib\shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\\Users\\MrD\\.PyCharm40\\config\\scratches\\testfile:'
应该如此。
这是一个错误吗?
上下文:我正在测试我的代码在给出非法文件名时的行为(: 在 Windows 文件名中是非法的),令我惊讶的是,我的程序删除了原始文件(糟糕!)并创建了一个大小为零的文件原始属性(是的,在我的情况下,文件 已创建,只是空的)和文件名 放弃给: 的文件名 - 所以像textfile:.jpg 这样的文件名给了我一个零字节@987654330 @。花了很多时间调试 - 这是 Python27\lib\shutil.py copyfile() 中的小动物(上面吹但没有吹的那条线):
我不知道为什么在我的情况下文件是在运行脚本时创建的。
【问题讨论】:
-
@PadraicCunningham:它是开放的,应该会爆炸并且不会在源代码中仔细查看 - 在回溯中可以看到开放会爆炸,但在这里它不会。
open当然是特定于操作系统的。因为这个原因,shutil.move 恰好表现得非常糟糕 - 就像取消链接文件而不是吹一样。我可能应该编辑这个问题,但现在我需要休息一下 - 相信我这个问题的来源相当复杂。
标签: python python-2.7 shutil