Shutil and for questions

Asked 2 years ago, Updated 2 years ago, 99 views

import glob

import shutil

import os

import sys


filename =  glob.glob('**/*.jpg', recursive=True)

filename =
 [os.path.basename(name) for name in filename]

for name in filename:

    if not os.path.exists('jpg_files'):
        os.mkdir('jpg_files')
    jpg_files = 'jpg_files'
    shutil.copy (name, os.path.join (jpg_files, name))
    print(name)

Hello~~ I'm trying to make a tool to copy only the files I want

I can't copy anything,다시피 As you can see above code, in the folder where this Python file is located

I want to collect jpg files separately and copy them to a newly created folder called jpg_files.

I can't collect the files from the for statement, what's the reason?

filename = [os.path.basename(name) for name in filename] Until now, the jpg file is saved in the list format.

shutil for copy glob

2022-09-21 18:13

1 Answers

There seems to be no problem with the code, so I tested it. Works well on ubuntu 18.04 (4.15.0-50-generic).

In [2]: import glob 
   ...:  
   ...: ...: import shutil 
   ...:  
   ...: ...: import os 
   ...:  
   ...: ...: import sys 
   ...:  
   ...:  
   ...: ...: filename =  glob.glob('**/*.jpg', recursive=True) 
   ...:  
   ...: ...: filename = [os.path.basename(name) for name in filename]                

In [3]:                                                                         

In [3]: filename                                                                
Out[3]: ['FbzxIDl.jpg', 'i0859402069.jpg', 'CeZ7Tv8.jpg']

In [4]: for name in filename: 
   ...:  
   ...:     ...:     if not os.path.exists('jpg_files'): 
   ...:         ...:         os.mkdir('jpg_files') 
   ...:     ...:     jpg_files = 'jpg_files' 
   ...:     ...:     shutil.copy (name, os.path.join (jpg_files, name)) 
   ...:     ...:     print(name) 
   ...:                                                                         
FbzxIDl.jpg
i0859402069.jpg
CeZ7Tv8.jpg

In [5]: cd jpg_files/                                                                                                           
/home/allinux/aaaaa/jpg_files

In [6]: ls -al                                                                                                                  
a total of 300
drwxr-xr-x2 allinux allinux 4096 May 29 23:36./
drwxrwxr-x 3 allinux allinux 4096 May 29 23:36../
-rwxrwxrwx1 allinux allinux 123978 May 29 23:36 CeZ7Tv8.jpg*
-rwxrwxrwx1 allinux allinux 104089 May 29 23:36 FbzxIDl.jpg*
-rwxrwxrwx1 allinux allinux 61932 May 29 23:36 i0859402069.jpg*


2022-09-21 18:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.