-1

I have a whole bunch of files in a directory. I'd like a program to loop over the files in the directory and prompt me to enter the name of directory (which are all in the same directory) so that the program moves the file to the specified directory.

I'd like a terminal solution, more specifically, Python way would be instructive for me

tshepang
  • 12,111
  • 21
  • 91
  • 136
kan
  • 199
  • 9
  • 9
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, stack traces, compiler errors - whatever is applicable). The more detail you provide, the more answers you are likely to receive. – Martijn Pieters Jan 16 '13 at 14:41
  • Use the `os` and `shutil` libraries – Harpal Jan 16 '13 at 14:46
  • What are you trying to achieve different than what the normal shell provides for moving files? – Burhan Khalid Jan 16 '13 at 14:51
  • @MartijnPieters I agree with your POV. I'll get back with some code I have written. Thank you. – kan Jan 16 '13 at 14:54

1 Answers1

4

Your question is a bit vauge on what you need help with, but here is a template to get you started. Use os and shutil to list directories and move files.

import shutil, os

target = raw_input("Target directory: ")

# Make sure the target dir exists!
assert(os.path.exists(target))

for f in os.listdir('.'):
    b = raw_input("Press y to move file %s to %s: " %(f,target))
    if b.lower() == 'y':
        shutil.move(f, target)
Hooked
  • 84,485
  • 43
  • 192
  • 261
  • This is almost it! I can suitably modify this for my purposes. Thank you. – kan Jan 16 '13 at 15:00
  • BTW, can I ask you what happens if the target dir does not exist? – kan Jan 16 '13 at 15:54
  • @KannappanSampath Try it! What will happen is the `assert` command will fail since `os.path.exists(target)` will be false. `assert` is a really useful sanity check and can throw more useful exceptions if you want to expand it. – Hooked Jan 16 '13 at 15:57
  • Now, I actually did something more thrilling: I did not do the sanity check and so, I am wondering what would have happened to that file! – kan Jan 16 '13 at 16:00
  • 1
    @KannappanSampath My guess is that the file was renamed to `target`, as (I think) `shutil.move` is aware if it is moving to a directory destination or a file location. – Hooked Jan 16 '13 at 16:17