A.Starr A.Starr - 6 months ago 20
Python Question

Python: read a text file and copy/paste directories listed in it to a new directory

I am trying to read a .txt file that lists directory names and copy/paste the listed directories into a new directory. I am pretty close to figuring it out but need a function that copies the directory (not only its contents).

from distutils.dir_util import copy_tree

dst = '/Users/name/Desktop/Core/TEST'
f = open('/Users/name/Desktop/Core/Core_List.txt','r')
for i in f.readlines():
print i
copy_tree(i.strip(), dst)

f.close()





This is what ended up working:

from shutil import copytree
from os.path import join

dst = '/Users/name/Desktop/Core/TEST'
f = open('/Users/name/Desktop/Core/Core_List.txt','r')
for i in f.readlines():
print i
copytree(i.strip(), join(dst,i))

f.close()

Answer

Perhaps this

from shutil import copytree
from os.path import join

dst = '/Users/name/Desktop/Core/TEST'
with open('/Users/name/Desktop/Core/Core_List.txt') as f:
    for src in f:
       print src
       copytree(src, join(dst, src))

Assuming src is relative to the working directory, it's somewhat more complex if it's not.

Comments