Python Forum
I am trying to copy files into a bunch of folders.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am trying to copy files into a bunch of folders.
#4
Your code works fine for me. I switched it to .txt or .py, and in prints a bunch of Trues and Falses.

It is rather inefficient. You are checking each file twice, once to see if it's a Word doc, once to see if it's a PowerPoint file. It would be better to make a dictionary with file extensions as the keys, and folders they should be copied to as the values. Also, I would check with endswith rather than in. It's more precise and (again) more efficient.
import os
FileTypes = {'.txt': 'Text file','.py': 'Python program', '.xml': 'XML data'}
dirList = os.listdir(os.getcwd())
for item in dirList:
    for extension, folder in FileTypes.items():
        if item.endswith(extension):
            print(folder)
            break
    else:
        print('Other')
See how I used break? It only checks until it finds something, then it stops checking the other extensions. We can also use the else clause to catch anything to didn't match the extensions we were looking for.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
RE: I am trying to copy files into a bunch of folders. - by ichabod801 - Apr-22-2017, 10:35 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Using zipfile module - finding folders not files darter1010 2 423 Apr-06-2024, 07:22 AM
Last Post: Pedroski55
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 372 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  Copy Paste excel files based on the first letters of the file name Viento 2 553 Feb-07-2024, 12:24 PM
Last Post: Viento
  Create new folders and copy files cocobolli 3 1,635 Mar-22-2023, 10:23 AM
Last Post: Gribouillis
  Copy only hidden files and folders with rsync Cannondale 2 1,107 Mar-04-2023, 02:48 PM
Last Post: Cannondale
  a bunch of modules to import Skaperen 2 951 Nov-07-2022, 07:33 PM
Last Post: Gribouillis
  Compare filename with folder name and copy matching files into a particular folder shantanu97 2 4,658 Dec-18-2021, 09:32 PM
Last Post: Larz60+
  Moving files to Folders giddyhead 13 9,415 Mar-07-2021, 02:50 AM
Last Post: giddyhead
  How to use Bunch data structure moish 2 3,017 Dec-24-2020, 06:25 PM
Last Post: deanhystad
  code to read files in folders and transfer the file name, type, date created to excel Divya577 0 1,928 Dec-06-2020, 04:14 PM
Last Post: Divya577

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020