使用 python 将文件复制到另一个文件夹
Copy files to another folder using python
比方说,我有一个包含 10k 文件的源文件夹,我想将 1k 文件复制到另一个文件夹。尝试了以下方法,它有效但是,有什么方法可以更有效地做到这一点?
sourceFiles = os.listdir("/source/")
destination = "/destination/"
for file in sourceFiles[0 : 1000]:
shutil.copy(file, destination)
我的感受是,我将 10k 个文件加载到一个列表变量中,并迭代列表中的每个元素 1k 次,将不需要的数据加载到 RAM 中,这对我来说不太好。有没有更好的方法来做同样的事情?
如果您使用的是 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
它使用了一个生成器并且语法更简洁恕我直言。
它在内存效率上也更好。看:
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
>>>
比方说,我有一个包含 10k 文件的源文件夹,我想将 1k 文件复制到另一个文件夹。尝试了以下方法,它有效但是,有什么方法可以更有效地做到这一点?
sourceFiles = os.listdir("/source/")
destination = "/destination/"
for file in sourceFiles[0 : 1000]:
shutil.copy(file, destination)
我的感受是,我将 10k 个文件加载到一个列表变量中,并迭代列表中的每个元素 1k 次,将不需要的数据加载到 RAM 中,这对我来说不太好。有没有更好的方法来做同样的事情?
如果您使用的是 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
它使用了一个生成器并且语法更简洁恕我直言。
它在内存效率上也更好。看:
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
>>>