-1

I have several folders that have a naming convention of "monthly_vendor_report_####", where #### is just a random combination of numbers. Each folder has a CSV file and I'd like to move the CSVs files out of the folder to a new destination source. So far this is what I have, which only unzips the files:

import os, zipfile

dir_name = r"C:\Users\...."
extension = ".zip"

os.chdir(dir_name) # change directory from working dir to dir with files

for item in os.listdir(dir_name): # loop through items in dir
    if item.endswith(extension): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        zip_ref = zipfile.ZipFile(file_name) # create zipfile object
        zip_ref.extractall(dir_name) # extract file to dir
        zip_ref.close() # close file
        os.remove(file_name) # delete zipped file

Screenshot of folders--each folder contains a CSV

Content of one of the folders

cfort
  • 2,655
  • 1
  • 19
  • 29
Max Lee
  • 1
  • 2

1 Answers1

0

You can use shutil to copy or move the files.

#Note that all the CSV files are taking the same names as their folders

import os
import shutil

# Open a file
path = 'C:\foo'
os.chdir(path)

dirs = filter(os.path.isdir, os.listdir(path))

destination= 'C:\Output'

# This would copy all listed CSV files 
for dir in dirs:
   file= dir + ".csv" 
   src= path + "\\" + dir + "\\" + file 
   shutil.copy(src, destination)
AziMez
  • 2,014
  • 1
  • 6
  • 16