7

I know this is going to be frustratingly easy for many of you. I am just beginning to learn Python and need help with some basic file handling.

I take a lot of screenshots, which end up on my desktop (as this is the default setting). I am aware I can change the screenshot setting to save it somewhere else automatically. However, I think this program will be a good way to teach me how to sort files. I would like to use python to automatically sort through all the files on my desktop, identify those that end with .png (the default file type for screenshots), and simply move it to a folder I've named "Archive".

This is what I've got so far:

import os
import shutil
source = os.listdir('/Users/kevinconnell/Desktop/Test_Folder/')
destination = 'Archive'
for files in source:
    if files.endswith('.png'):
        shutil.move(source, destination)

I've played around with it plenty to no avail. In this latest version, I am encountering the following error when I run the program:

Traceback (most recent call last): File "pngmove_2.0.py", line 23, in shutil.move(source, destination) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 290, in move TypeError: coercing to Unicode: need string or buffer, list found

I am under the impression I have a sort of issue with the proper convention/syntax necessary for the source and destination. However, I've thus far been unable to find much help on how to fix it. I used os.path.abspath() to determine the file path you see above.

Thanks in advance for any help in preserving my sanity.

LATEST UPDATE

I believe I am very close to getting to the bottom of this. I'm sure if I continue to play around with it I'll figure it out. Just so everyone that's been helping me is updated...

This is the current code I'm working with:

import os
import shutil
sourcepath ='/Users/kevinconnell/Desktop/'
source = os.listdir(sourcepath)
destinationpath = '/Users/kevinconnell/Desktop/'
for files in source:
    if files.endswith('.png'):
        shutil.move(os.path.join(sourcepath,'Test_Folder'), os.path.join(destinationpath,'Archive'))

This works for renaming my 'Test_Folder' folder to 'Archive'. However, it moves all the files in the folder, instead of moving the files that end with '.png'.

tshepang
  • 12,111
  • 21
  • 91
  • 136
nivackz
  • 71
  • 1
  • 1
  • 4

4 Answers4

10

You're trying to move the whole source folder, you need to specify a file path

import os
import shutil
sourcepath='C:/Users/kevinconnell/Desktop/Test_Folder/'
sourcefiles = os.listdir(sourcepath)
destinationpath = 'C:/Users/kevinconnell/Desktop/Test_Folder/Archive'
for file in sourcefiles:
    if file.endswith('.png'):
        shutil.move(os.path.join(sourcepath,file), os.path.join(destinationpath,file))
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
  • I'd also recommend using os.path.join instead of + – AMacK May 09 '14 at 03:26
  • @AMacK i have showed him what is wrong, please update my answer. so that i can learn better – sundar nataraj May 09 '14 at 03:27
  • @nivackz i said where did error caused since u r sending source which is list of files but shutill.move need single file. that what i meant. he said he prefer using os.join.path to join the sourcepath+file name. Please there is nothing against u – sundar nataraj May 09 '14 at 03:35
  • Sorry it took me a bit to get back. I think you covered everything I noticed, although there's a missing "/" at the beginning of destination path. – AMacK May 09 '14 at 03:43
  • 1
    @AMacK thanks for ur idea. Really os.path.join is must. some times v forget giving slashes properly or it takes as special character – sundar nataraj May 09 '14 at 03:46
7

Another option is using glob module, which let's you specify file mask and retrieve list of desired files. It should be as simple as

import glob
import shutil

# I prefer to set path and mask as variables, but of course you can use values
# inside glob() and move()

source_files='/Users/kevinconnell/Desktop/Test_Folder/*.png'
target_folder='/Users/kevinconnell/Dekstop/Test_Folder/Archive'

# retrieve file list
filelist=glob.glob(source_files)
for single_file in filelist:
     # move file with full paths as shutil.move() parameters
    shutil.move(single_file,target_folder) 

Nevertheless, if you're using glob or os.listdir, remember to set full paths for source file and target.

Community
  • 1
  • 1
Gabriel M
  • 710
  • 4
  • 7
0

Based on @Gabriels answer. I have put some effort into this as, I like to "Categorize" my file types into folders. I now use this.

I believe this is what you are looking for, this was fun to figure out

This Script:

  • Shows Example files to be moved until you uncomment shutil.move
  • Is in Python3
  • Was Designed On a MacOSX
  • Will not create folders for you, it will throw an error
  • Can find and move files with extension you desire
  • Can be used to Ignore folders
    • Including the destination folder, should it be nested in your search folder
  • Can be found in my Github Repo

Example from Terminal:

$ python organize_files.py
filetomove: /Users/jkirchoff/Desktop/Screen Shot 2018-05-15 at 12.16.21 AM.png
movingfileto: /Users/jkirchoff/Pictures/Archive/Screen Shot 2018-05-15 at 12.16.21 AM.png

Script:

I named organize_files.py

#!/usr/bin/env python3

# =============================================================================
# Created On  : MAC OSX High Sierra 10.13.4 (17E199)
# Created By  : Jeromie Kirchoff
# Created Date: Mon May 14 21:46:03 PDT 2018
# =============================================================================
# Answer for: https://stackoverflow.com/a/23561726/1896134 PNG Archive
# NOTE: THIS WILL NOT CREATE THE DESTINATION FOLDER(S)
# =============================================================================

import os
import shutil

file_extensn = '.png'
mac_username = 'jkirchoff'

search_dir = '/Users/' + mac_username + '/Desktop/'
target_foldr = '/Users/' + mac_username + '/Pictures/Archive/'
ignore_fldrs = [target_foldr,
                '/Users/' + mac_username + '/Documents/',
                '/Users/' + mac_username + '/AnotherFolder/'
                ]

for subdir, dirs, files in os.walk(search_dir):
    for file in files:
        if subdir not in ignore_fldrs and file.endswith(file_extensn):
            # print('I would Move this file: ' + str(subdir) + str(file)
            #       # + "\n To this folder:" + str(target_foldr) + str(file)
            #       )

            filetomove = (str(subdir) + str(file))
            movingfileto = (str(target_foldr) + str(file))
            print("filetomove: " + str(filetomove))
            print("movingfileto: " + str(movingfileto))

            # =================================================================
            # IF YOU ARE HAPPY WITH THE RESULTS
            # UNCOMMENT THE SHUTIL TO MOVE THE FILES
            # =================================================================
            # shutil.move(filetomove, movingfileto)

            pass
        elif file.endswith(file_extensn):
            # print('Theres no need to move these files: '
            #       + str(subdir) + str(file))
            pass
        else:
            # print('Theres no need to move these files either: '
            #       + str(subdir) + str(file))
            pass
JayRizzo
  • 3,234
  • 3
  • 33
  • 49
0
import os
import shutil
Folder_Target = input("Path Target which Contain The File Need To Move it: ")
File_Extension = input("What Is The File Extension ? [For Example >> pdf , txt , exe , ...etc] : ")
Folder_Path = input("Path To Move in it : ")
Transformes_Loges = input("Path To Send Logs Of Operation in : ")
x=0
file_logs=open(Transformes_Loges+"\\Logs.txt",mode="a+")

for folder, sub_folder, file in os.walk(Folder_Target):
    for sub_folder in file:
        if os.path.join(folder, sub_folder)[-3:]==File_Extension:
           path= os.path.join(folder, sub_folder)
           file_logs.write(path+" =====================  Was Moved to ========================>> "+Folder_Path )
           file_logs.write("\n")
           shutil.move(path, Folder_Path)
           x+=1
file_logs.close()
print("["+str(x)+"]"+"File Transformed")