Reputation: 317
A file writing some files name list, such as there are files names
f1
f2
f3
And In the one directory, there are many files which including those files,such as
F2
f1
F3
f2
f3
I would like to copy the files which appear in the file list. And my scripts whose error is *TypeError*as below,
import sys
import shutil,errno
import os
srcDir = 'Root'
dstDir = 'De'
with open('file.txt','r') as f:
read_filename = f.read()
f.closed
for files in os.walk(srcDir)
if files in read_filename:
shutil.move(srcDir,dstDir)
Upvotes: 0
Views: 51
Reputation: 1121554
You need to turn the first file into a set (for fast membership testing). You are also using os.walk
, which gives you three pieces of information, the path to the directory, a list of subdirectories and a list of the files in that directory:
import sys
import shutil,errno
import os
srcDir = 'Root'
dstDir = 'De'
with open('file.txt','r') as f:
read_filenames = {fname.strip() for fname in f} # set comprehension
for root, directories, files in os.walk(srcDir):
for filename in read_filenames.intersection(files):
shutil.move(os.path.join(root, filename), dstDir)
The .intersection()
call returns all elements in the read_filenames
set that are also in the files
list.
Note that I tell shutil.move()
the full path of the file to move to dstDir
, using os.path.join()
based on the root
variable (path of the directory the file is in) and the filename.
Upvotes: 1