[英]Copy files to another folder using python
Lets say, i have a source folder with 10k file, i want to copy 1k files to another folder.假设,我有一个包含 10k 文件的源文件夹,我想将 1k 文件复制到另一个文件夹。 Tried the below methods, it worked but, is there any way to do it more efficiently ?尝试了以下方法,它奏效了,但是有什么方法可以更有效地做到这一点?
sourceFiles = os.listdir("/source/")
destination = "/destination/"
for file in sourceFiles[0 : 1000]:
shutil.copy(file, destination)
Here what i feel is, i am loading 10k files into a list variable and iteration through each element in the list for 1k times, loading unwanted data into the RAM, which doesn't look good for me.我的感觉是,我将 10k 个文件加载到列表变量中,并迭代列表中的每个元素 1k 次,将不需要的数据加载到 RAM 中,这对我来说并不好。 Is there any better way to do the same ?有没有更好的方法来做同样的事情?
If you are using Python 3, pathlib.Path.iterdir
is a better option:如果您使用的是 Python 3, pathlib.Path.iterdir
是更好的选择:
from pathlib import Path
source = Path('/source')
target = Path('/destination')
counter = 0
for obj in source.iterdir():
if obj.is_file():
obj.rename(target / obj.name)
counter += 1
if counter > 1000:
break
It uses a generator and the syntax is cleaner IMHO.它使用生成器,语法更简洁恕我直言。
It is also better on memory efficiency.它在内存效率上也更好。 Look:看:
Python 3.7.5 (default, Dec 15 2019, 17:54:26)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys import getsizeof
>>> from os import listdir
>>> from pathlib import Path
>>> files = listdir('/usr/bin')
>>> usrbin = Path('/usr/bin')
>>> getsizeof(files)
26744
>>> getsizeof(usrbin.iterdir())
128
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.