DivZ
DivZ

Reputation: 728

How to copy files containing certain string using Shutil?

I've been tasked with writing a very simple script but I can't for the life of me figure out how to...

All I need to do is use the module Shutil to copy all files that contains "Tax_" from ~/Documents folder to my current working directory.

import shutil
import os

src = os.path.expanduser('~/Documents/Tax 2018')
dst = os.getcwd()

for files in src:
    if 'bdd' in files: # also tried: if files.startswith("Tax_")
        shutil.copy(files,dst)

Does not work. We were also given the option of finding files with Shutil.which("Tax_") but that simply doesn't work.

Upvotes: 1

Views: 3906

Answers (4)

hongkail
hongkail

Reputation: 789

Please try:

import glob
import os
import shutil

dst = os.getcwd()
str_target = 'bdd'     # OR 'Tax_'

f_glob = "~/Documents/Tax 2018/{}*.txt".format(str_target)
ls_f_dirs = glob.glob(f_glob)

for f_dir in ls_f_dirs:
    shutil.copy(f_dir, dst)

Upvotes: 0

FortaTune
FortaTune

Reputation: 36

Make sure to give the files a file type and hopefully this will work for you:

#!/usr/bin/env python3

#Imports
from shutil import copyfile
import shutil
import os

# Assigning the variables to search and the location
file_str = "Tax_201"
search_path = os.path.join(os.path.expanduser('~'),'Documents')

# Repeat for each file in the search path
for filename in os.listdir(path=search_path):
    # Check if the file starts with Tax_2018
    if filename.startswith(file_str):
        # Assigning the variables for the src and destination
        path_src = os.path.join(os.path.expanduser('~'),'Documents', filename)
        path_destination = os.path.join(os.path.expanduser('~'),'Documents', 'Taxes', filename)
        # Copy the file that matched the file_str
        shutil.copyfile(path_src, path_destination)
    else:
        # Stop the loop
        break

Output

Documents/
├── Taxes
├── Tax_2018.txt
├── Tax_2019.txt
Documents/Taxes/
├── Tax_2018.txt
├── Tax_2019.txt

Upvotes: 1

probat
probat

Reputation: 1532

Maybe something like this will work for you. It asks you for the input directory and then asks you where you want to save the files. If the save directory does not exist then it is created, if the save directory already exists then it simply continues. The final input() function is just there to leave up the python console so you can see it has finished.

The benefit of using shutil.copy2 is that it attempts to preserve the metadata of the files.

Also depending on how your files are named, you weren't very specific you may need to slightly alter this line if 'tax_' in file.lower():.

import shutil
import os


input_dir = input('Please enter directory that contains that tax files.\n')
output_dir = input('\nPlease enter the path where you want to save the files.\n')


for file in os.listdir(input_dir):
    if 'tax_' in file.lower():

        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        shutil.copy2(os.path.join(input_dir, file), os.path.join(output_dir, file))

input('\nFinished --> Files are saved to %s' % output_dir)  # format() or f strings are ideal but not sure which python version you have

Upvotes: 1

jacalvo
jacalvo

Reputation: 666

You can try something like this:

from glob import glob

for file in glob('~/Documents/Tax 2018/Tax_*'):
    shutil.copy(file, dst)

glob will return a list of file matching the wildcard pattern, int his case those files Starting with Tax_ on the given path.

Upvotes: 2

Related Questions