2008-10-30 26 views
6

假设我有一个输入文件和一个目标目录。如何确定输入文件是否与目标目录位于同一个硬盘驱动器(或分区)上?如何确定一个目录是否在同一分区

我想要做的是复制一个文件,如果它不同,但移动它,如果它是相同的。例如:

target_directory = "/Volumes/externalDrive/something/" 
input_foldername, input_filename = os.path.split(input_file) 
if same_partition(input_foldername, target_directory): 
    copy(input_file, target_directory) 
else: 
    move(input_file, target_directory) 

由于CesarB的回答,same_partition功能实现:

import os 
def same_partition(f1, f2): 
    return os.stat(f1).st_dev == os.stat(f2).st_dev 

回答

11

在C语言中,你可以使用stat()和比较st_dev领域。在Python中,os.stat应该这样做。

+0

请注意,这不会在Windows上工作,这会使所有驱动器的st_dev都为0。 (因为他指定了osX和linux标签,可能对提问者不是问题) – Brian 2008-10-30 17:09:59

3

另一种方法是“更好地请求宽恕比权限”方法 - 只是尝试重命名它,如果失败,请抓住相应的OSError并尝试复制方法。即:

import errno 
try: 
    os.rename(source, dest): 
except IOError, ex: 
    if ex.errno == errno.EXDEV: 
     # perform the copy instead. 

这样做的好处是,它也可以在Windows上工作,其中st_dev对于所有分区始终为0。

请注意,如果你真的想复制,然后删除源文件(即执行移动),而不仅仅是复制,然后将shutil.move已经做你想要什么:

 
Help on function move in module shutil: 

move(src, dst) 
    Recursively move a file or directory to another location. 

    If the destination is on our current filesystem, then simply use 
    rename. Otherwise, copy src to the dst and then remove src. 

[编辑]由于马修Schinckel的评论更新提到shutil.move将删除复制后的来源,这不一定是想要的,因为问题只是提到复制。

+0

不完全一样。 OP似乎并不希望原始文件被删除,如果它们位于不同的磁盘上。 – 2008-11-03 06:47:18

相关问题