递归地复制文件 [英] Recursively copying files with progress

查看:149
本文介绍了递归地复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到过关于Python和复制文件的问题,但我有一个不同的方案来处理。

I've seen questions asked here before about Python and copying files, but I have a different scenario to deal with.

我几乎完成了一个Linux distro安装程序我一直在努力,现在所有它需要做的是将文件复制到目标分区。因为大多数的发行版安装程序都有一个进度条,我希望添加一个。

I'm almost done with a Linux distro installer I've been working on, and now all it needs to do is copy the files over to the destination partition. As most distro installers have a progress bar, I was hoping to add one too.

现在,我使用PyQt4,我的代码看起来像这样:

Right now, I'm using PyQt4 and my code looks like this:

self.status('Counting files...')
self.count = int(check_output(['-c', 'find /opt/linux/work/root-image/ -type f | wc -l'], stderr = PIPE, shell = True))

self.status('Copying files...')

i = 0

for root, dirs, files in os.walk('/opt/linux/work/root-image/'):
  for file in files:
    i += 1
    f = os.path.join(root, file)

    try:
      os.system('mkdir -p /tmp/foo' + os.path.split(f)[0])
    except:
      pass

    os.system('cp ' + f + ' /tmp/foo' + f)

    if i % 100 == 0:
      self.emit(SIGNAL('progress(int)'), int(100.0 * float(i) / float(self.count)))

self.status('Done...')

这是相当低效的,因为进度条。整个图像是 2.1GB ,并且它需要脚本真的很长时间来复制文件。

It's quite inefficient because of the progress bar. The whole image is 2.1GB, and it takes the script a really long time to copy the files over. Much longer than a simple cp -r.

是否有效的方法做这个?对于单文件复制进度条,你所做的一次只读小块,但我不知道如何做一个目录与 91,489 文件。

Is there any efficient way to do this? For single-file copy progressbars, all you do is read little chunks at a time, but I have no idea how to do that for a directory with 91,489 files.

任何帮助都会有所帮助。感谢!

Any help would be helpful. Thanks!

推荐答案

您可以尝试使用 shutil.copy 而不是使用 os.system (它创建一个单独的进程)调用到操作系统。您也可以使用 os.mkdir 创建新目录。但是,你确定它是因为进度条缓慢,而不是其他吗?

You could try using shutil.copy to copy files instead of calling out to the OS using os.system (which creates a separate process). You can also use os.mkdir to create new directories. However, are you sure that it is slow because of the progress bar and not something else?

这篇关于递归地复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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