HI
I need to copy .dll files in C:\Windows\system32\ which is found or match in my my_file.txt file to C:\tools folder.

my code not work and need also to found words that can match my_file.txt.
so for example I have RICHED20.dll in my my_file.txt if the same file name"RICHED20.dll" exist in C:\Windows\system32\ the RICHED20.dll copy to my C:\tools

import os
import shutil
source = os.listdir "C:\Windows\system32\"
destination = "C:\tools"
for files in source:
    if files.endswith(".dll"):
        shutil.move(files,destination)

my_file.txt

dbghelp.dll
RICHED20.dll
Riched32.dll
napinsp.dll
wshbth.dll
cscapi.dll
pnrpnsp.dll
winrnr.dll
rasadhlp.dll

Recommended Answers

All 2 Replies

#the following will copy any dll files in my_file.txt from
#C:\Windows\Sytem32 to C:\Tools
import os
import shutil

sourcedir = "C:\\Windows\\System32"

source = os.listdir(sourcedir)

destination = "C:\\Tools"  

dllmatch = open("my_file.txt", "r")    # may need full path here

matchf = dllmatch.readlines()

for i in range(0,len(matchf)):
    if matchf[i][-1] == "\n":
        matchf[i] = matchf[i][:-1]    # :-1 to strip off \n

for files in source:
    if files in matchf:
        if os.path.splitext(files)[1] == ".dll":
            shutil.copy(os.path.join(sourcedir,files),destination)

Good effort Peter 18,the code dos what it shall.
I would suggest some improvements.
To strip off \n is better to use strip()

>>> s = 'hello\n'
>>> s.strip()
'hello'

So code under can be one line matchf = [i.strip() for i in dllmatch]

matchf = dllmatch.readlines()

for i in range(0,len(matchf)):
    if matchf[i][-1] == "\n":
        matchf[i] = matchf[i][:-1]    # :-1 to strip off \

Complete code with a couple more changes.

import os
import shutil    

source = os.listdir("C:\\Windows\\System32")
destination = "C:\\Tools"  

with open('my_file.txt') as f_obj:
    matchf = [i.strip() for i in f_obj]

for files in source:
    if files.endswith('.dll') and files in matchf:
        shutil.copy(os.path.join(sourcedir, files), destination)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.