Search code examples
pythontext-filescopy-pastefile-manipulation

How do I copy all files of one specific type from a folder to another folder in Python


Im trying to copy a numerous amount of .txt files from one folder to another using a Python script. I dont want to copy one single file at a time, and im not even sure exactly how many txt files are present in the folder. I am looking to scan the folder and copy all text files from it to another folder. I have already tried doing this using the shutil and os libraries to no avail. Can someone please help?

import os
import shutil
def start():
    dest = "C:/Users/Vibhav/Desktop/Txt"
    source = "C:/Users/Vibhav/Desktop/Games"
    for file in os.listdir("C:/Users/Vibhav/Desktop/Games"):
        if file.endswith(".txt"):
        shutil.copy2(dest,source)           

This is what I have tried doing, but it doesnt work for me. I keep getting this error

PermissionError: [Errno 13] Permission denied: 'C:/Users/Vibhav/Desktop/Games'

It would really help me if someone could help me out


Solution

  • Main mistake: you're trying to copy the directory, not the file.

    Rewriting using glob.glob to get pattern filtering + absolute path sounds the best option:

    def start():
        dest = "C:/Users/Vibhav/Desktop/Txt"
        source = "C:/Users/Vibhav/Desktop/Games"
        for file in glob.glob(os.path.join(source,"*.txt")):
            shutil.copy2(file,dest)