Patrick
Patrick

Reputation: 2544

Copy files recursively

def ignore_list(path, files):
    filesToIgnore = []
    for fileName in files:
        fullFileName = os.path.join(os.path.normpath(path), fileName)
        if not os.path.isdir(fullFileName) and not fileName.endswith('pyc') and not fileName.endswith('ui') and not fileName.endswith('txt') and not fileName == '__main__.py' and not fileName == 'myfile.bat':
            filesToIgnore.append(fileName)

    return filesToIgnore

# Start of script    
shutil.copytree(srcDir, dstDir, ignore=ignore_list)

I want to change the if line containing files to copy. Here I have to give the filenames separately, but I want to change it like it should take filenames from a list containing all file names.

How can I do this?

Upvotes: 1

Views: 125

Answers (2)

flazzarini
flazzarini

Reputation: 8171

You could also write a method like the following.

def ignore_files(path, extensions, wantedfiles):
      ignores = []

      for root, dirs, filenames in os.walk(path):
          for filename in filenames:
            if any(filename.endswith(_) for _ in extensions):
                  ignores.append(os.path.join(os.path.normpath(path), filename))
            elif filename in wantedfiles:
                  ignores.append(os.path.join(os.path.normpath(path), filename))

      return ignores

# Start of script
ignore_list = ignore_files(srcDir, ['pyc', 'uid', 'txt'])
shutil.copytree(srcDir, dstDir, ignore=ignore_list)

Upvotes: 0

Ankit Jaiswal
Ankit Jaiswal

Reputation: 23427

What I could understand from your question is, you could simply write:

if fileName not in fileNameList:
    filesToIgnore.append(fileName)

where fileNameList is a list of file names which you want to copy.

Update:

fName, fileExtension = os.path.splitext(fileName)
if fileName not in fileNameList or fileExtension not in allowedExtensionList:
    filesToIgnore.append(fileName)

Upvotes: 1

Related Questions