简体   繁体   English

使用python将文件复制到另一个文件夹

[英]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.

相关问题 使用python将某些文件复制到另一个文件夹 - Copy certain files from one folder to another using python 使用python脚本将一个文件夹中的多个jpeg文件和json文件复制并排序到子文件夹文件夹中的另一个文件夹 - copy and sort multiple jpeg files and json files in one folder to another folder in subfolders folder using python script 将文件复制到另一个文件夹,避免在 python 中重复 - copy files to another folder, avoiding duplication in python 将n个文件复制到另一个文件夹的Python脚本 - Python script to copy n files to another folder 使用具有完整文件夹结构的 python 复制文件 - Copy files using python with complete folder structure Python将文件复制到文件夹 - Python copy files to folder 有没有办法使用 python 中该文件名的子文本将文件从一个文件夹复制到另一个文件夹? - Is there a way to copy files from one folder to another using a subtext of that file name in python? 如何使用 Python 将 zipfile 从一个文件夹复制到另一个文件夹 - How to copy zipfile from one folder to another folder using Python 如何将从 txt 文件中选择的文件复制到另一个文件夹 python - How to copy files selected from a txt file to another folder python Python:将文件从一个文件夹复制到2天前创建的另一个文件夹 - Python: Copy files from a folder to another that created 2 days ago
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM