Python - copying specific files from a list into a new folder

前端 未结 2 1354
长情又很酷
长情又很酷 2021-01-15 11:02

I am trying to get my program to read a list of names from a file (say .txt), then search for those in a selected folder and copy and paste those files to another selected f

相关标签:
2条回答
  • 2021-01-15 11:30

    Your last section has a problem.

    for file in os.listdir(folderPath): 
        for file in files:
            if file in filesToFind:
                shutil.copy(file, destination)
    

    The first for loops over each filename in the directory, which is perfectly understandable.

    The second for is an error, because files does not exist. What did you intend it to do?

    0 讨论(0)
  • 2021-01-15 11:36

    The last part of your program might work better this way:

    for file in files:
        if file in filesToFind:
            name = os.path.join( folderPath, file )
            if os.path.isfile( name ) :
                shutil.copy( name, destination)
            else :
                print 'file does not exist', name
    

    Otherwise it's pretty much unknown where you copy your files from, current folder, maybe, and why did you need to input folderPath earlier, if you don't use it.

    btw, file is a reserved word in python, I'd recommend to use another name for your variable, that does not coincide with python reserved words.

    0 讨论(0)
提交回复
热议问题