1

I am trying to move files, that has same names from different folders to new folder keeping the folder structure but each time getting same error

Errno20

  • so in one directory I have three folders
  • each folder has its own logs.txt file
    ls esxi*
    esxi1:
    logs.txt
    
    esxi2:
    logs.txt
    
    esxi3:
    logs.txt
  • I can find them with python3:
>>> for i in glob.glob('**/*.txt', recursive=True):
...   print(i)
...
esxi3/logs.txt
esxi2/logs.txt
esxi1/logs.txt
case1/logs.txt

...now when trying to move them, getting same error:

>>> for i in glob.glob('**/*.txt', recursive=True):
...   shutil.copytree(i, 'case1',  dirs_exist_ok=True)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib/python3.8/shutil.py", line 555, in copytree
    with os.scandir(src) as itr:
NotADirectoryError: [Errno 20] Not a directory: 'esxi3/logs.txt'
>>>

used both .copy2() & copytree() and always getting not a directory error,

Can you help me moving files with their directories please ?

NOTE: there is more files in those directories and I only want to copy those specific logs.txt files...

thanks!

  • https://stackoverflow.com/questions/41826868/moving-all-files-from-one-directory-to-another-using-python ill post an answer in a second – Jonathan Coletti Oct 22 '21 at 16:50

1 Answers1

1

with "copytree" you need copy the directory not the files inside it, like this :

for n,i in enumerate (glob.glob('./esx*', recursive=True)):
    shutil.copytree(i, "/tmp/zied/"+str(n))
    

and if you want to persist the directories name then :

import os 

for n,i in enumerate (glob.glob('./esx*', recursive=True)):
    shutil.copytree(i, "/tmp/zied/"+os.path.basename(i))
    
sbabti zied
  • 784
  • 5
  • 17