从本地linux文件夹移动到装有cifs的windows共享

2024-04-20 09:52:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将脚本中的文件从ext4hdd上的本地文件夹移动到一个安装了windows共享的文件夹中,比如:mount -t cifs -o username=username,password=password,rw,nounix,iocharset=utf8,file_mode=0777,dir_mode=0777 //192.168.1.120/storage /mnt/storage

我试图使用os.rename(src,dst)shutil.move(src,dst)甚至subprocess.call(['mv', src,dst], Shell=True)或{}

获取每个文件的错误,根据我所知,是因为linux文件所有权/权限。。在

例如,mv /mnt/networkshare/file1.txt /tmp/file1.txt很好,但是

mv /tmp/file1.txt /mnt/networkshare/file1.txt

结果

^{pr2}$

我假设os.rename(src,dst)shutil.move(src,dst)也会出现同样的问题,但他们并不那么健谈。在

shutil.move(src,dst)告诉我:[Errno 1]不允许的操作:'/mnt/networkshare/file1.txt'

并且os.rename(src,dst)表示:[Errno 18]跨设备链接无效

编辑:pcmanfm能够从本地到远程剪切和粘贴。在

加上。。令我困惑的是有些文件被移走了。。在


Tags: 文件srctxt文件夹moveosusernamepassword
1条回答
网友
1楼 · 发布于 2024-04-20 09:52:19

os.rename无法跨文件系统移动文件,因为底层的^{} syscall不允许:

rename() does not work across different mount points, even if the same filesystem is mounted on both.

至于shutil.move失败的原因,答案也在于its documentation

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

那我们check ^{}吧!在

Similar to copy(), but metadata is copied as well – in fact, this is just copy() followed by copystat()

所以,copystat失败了-因为它不能在这样的挂载上设置文件元数据。在

由于shutil似乎没有一个方法可以在不复制元数据的情况下重命名,因此我们必须自己来做。让我们看看它的源代码:

In [3]: print inspect.getsource(shutil.move)
def move(src, dst):
    """Recursively move a file or directory to another location. This is
    similar to the Unix "mv" command.

    If the destination is a directory or a symlink to a directory, the source
    is moved inside the directory. The destination path must not already
    exist.

    If the destination already exists but is not a directory, it may be
    overwritten depending on os.rename() semantics.

    If the destination is on our current filesystem, then rename() is used.
    Otherwise, src is copied to the destination and then removed.
    A lot more could be done here...  A look at a mv.c shows a lot of
    the issues this implementation glosses over.

    """
    real_dst = dst
    if os.path.isdir(dst):
        if _samefile(src, dst):
            # We might be on a case insensitive filesystem,
            # perform the rename anyway.
            os.rename(src, dst)
            return

        real_dst = os.path.join(dst, _basename(src))
        if os.path.exists(real_dst):
            raise Error, "Destination path '%s' already exists" % real_dst
    try:
        os.rename(src, real_dst)
    except OSError:
        if os.path.isdir(src):
            if _destinsrc(src, dst):
                raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
            copytree(src, real_dst, symlinks=True)
            rmtree(src)
        else:
            copy2(src, real_dst)
            os.unlink(src)

看来,正如所预测的,我们所要做的就是用copy2替换copy。我们可以复制源代码并重命名函数,或者

^{pr2}$

如果你今天觉得幸运的话。理解the consequences of such留给读者作为练习

相关问题 更多 >