簡體   English   中英

使用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
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM