9.1.2 文件和文件夹的移动与改名

调用 shutil.move(source,  destination),将路径 source  处的文件夹移动到路径
destination,并返回新位置的绝对路径的字符串。
如果 destination 指向一个文件夹,source 文件将移动到 destination 中,并保持原来的文件名。例如,在交互式环境中输入以下代码:


>>>  import  shutil
>>>  shutil.move('C:\\bacon.txt',  'C:\\eggs')
'C:\\eggs\\bacon.txt'
假定在 C:\目录中已存在一个名为 eggs 的文件夹,这个 shutil.move()调用就是说,“将 C:\bacon.txt 移动到文件夹 C:\eggs 中。
如果在 C:\eggs  中原来已经存在一个文件 bacon.txt,它就会被覆写。因为用这种方式很容易不小心覆写文件,所以在使用 move()时应该注意。
destination  路径也可以指定一个文件名。在下面的例子中,source  文件被移动并改名。
>>>  shutil.move('C:\\bacon.txt',  'C:\\eggs\\new_bacon.txt')
'C:\\eggs\\new_bacon.txt'
这一行是说,“将 C:\bacon.txt  移动到文件夹 C:\eggs,完成之后,将 bacon.txt
文件改名为 new_bacon.txt。”
前面两个例子都假设在C:\目录下有一个文件夹 eggs。但是如果没有 eggs 文件夹,move()就会将 bacon.txt 改名,变成名为eggs 的文件。
>>>  shutil.move('C:\\bacon.txt',  'C:\\eggs')
'C:\\eggs'
这里,move()在 C:\目录下找不到名为 eggs 的文件夹,所以假定 destination 指的是一个文件,而非文件夹。所以 bacon.txt 文本文件被改名为 eggs(没有.txt 
文件扩展名的文本文件),但这可能不是你所希望的!这可能是程序中很难发现的缺陷,因为 move()调用会很开心地做一些事情,但和你所期望的完全不同。这也是在使用 move()时要小心的另一个理由。
最后,构成目的地的文件夹必须已经存在,否则 Python 会抛出异常。在交互式环境中输入以下代码:
>>>  shutil.move('spam.txt',  'c:\\does_not_exist\\eggs\\ham')
Traceback  (most  recent  call  last):
File  "C:\Python34\lib\shutil.py",  line  521,  in  move os.rename(src,  real_dst)
FileNotFoundError:  [WinError  3]  The  system  cannot  find  the  path  specified: 'spam.txt'  ->  
'c:\\does_not_exist\\eggs\\ham'
During  handling  of  the  above  exception,  another  exception  occurred: Traceback  (most  
recent  call  last):
File  "<pyshell#29>",  line  1,  in  <module>
shutil.move('spam.txt',  'c:\\does_not_exist\\eggs\\ham')
File  "C:\Python34\lib\shutil.py",  line  533,  in  move copy2(src,  real_dst)
File  "C:\Python34\lib\shutil.py",  line  244,  in  copy2 copyfile(src,  dst,  
follow_symlinks=follow_symlinks)
File  "C:\Python34\lib\shutil.py",  line  108,  in  copyfile with  open(dst,  'wb')  as  fdst:
FileNotFoundError:  [Errno  2]  No  such  file  or  directory:  'c:\\does_not_exist\\ eggs\\ham'
Python 在 does_not_exist 目录中寻找 eggs 和 ham。它没有找到不存在的目录所以不能将 spam.txt 移动到指定的路径。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大飞哥软件自习室

希望支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值