Catz
Catz

Reputation: 25

Copy files to folder

I want to copy those files with my keywords to a folder. How can I do that? This is my code:

from os import system, listdir, path
import codecs
FILE = open('C:\\Users\\Admin\\Desktop\\Test\\Result.txt', 'w') 
    desktop_dir =       path.join('C:\\Users\\Admin\\Desktop\\test\\')  
for fn in listdir(desktop_dir):
    fn_w_path = path.join(desktop_dir, fn)
    if path.isfile(fn_w_path):
        with open(fn_w_path, "r") as filee:  
            for line in filee.readlines():  
                for word in line.lower().split():
                    if word in {'James',
                                'Tim',
                                'Tom',
                                'Ian',
                                'William',
                                'Dennis',}:  
                        FILE.write(word + "\n")
FILE.close()

import os
import shutil

for root, dirs, files in os.walk("test_dir1", topdown=False):
    for name in files:
        current_file = os.path.join(root, name)
        destination = current_file.replace("test_dir1", "test_dir2")
        print("Found file: %s" % current_file)
        print("File copy to: %s" % destination)
        shutil.copy(current_file, destination)

Upvotes: 1

Views: 91

Answers (1)

SushilG
SushilG

Reputation: 731

You can use copyfile method that can copy your files to a directory.
Suppose you want to copy all files from src_directory to dest_directory

from shutil import copyfile
import os

src_directory = os.fsencode(directory_in_str)
dest_directory = os.fsencode(directory_in_str)

for file in os.listdir(src_directory):
   filename = os.fsdecode(file)
   copyfile(filename, os.path.join(dest_directory, filename))

Upvotes: 2

Related Questions