Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Python Tutorial - OS & Shutil Module #3

Python Tutorial - OS Module #3



OS Docs
Shutil Docs

If you have not read Python Tutorial - Modules #1 and Python Tutorial - Modules #2 I recommend you go and read them before reading this one.

In this tutorial we will be using another module called Shutil which will allows us to have a variety of options to edit or move files around.
Like I said in the last tutorial we are going to be adding more options to our little program.

First we are going to import Shutil, to do this all we have to do is follow OS by a comma for example
Code
import OS, shutil
Now we have the module imported we are able to use its assets.

Code
import os, shutil

path = "c:/users/william/pictures/pic.jpg"
path2 = "c:/users/william/pictures/hello.jpg"
moveDir = "c:/users/william/desktop"

if os.path.exists(path):
    print "Dir Exists!"
    print "Options:\n1 Remove Directory\n2 Move Directory\n3 Rename"
    q = raw_input("What would you like to do? ")
    if q == ("1"):
        os.remove(path)
    elif q == ("2"):
        shutil.move(path, moveDir)
    elif q == ("3"):
        os.renames(path, path2)
    else:
        print "Option does not exist!"

else:
    print "Dir Can Not Be Found!"

As you can see we have the same code from the last tutorial but we have used to shuil module to create an option which allows you to more that file to a different directory.
Idea: You could ask for the users input for a directory of there choice, but this will be fine for the tutorial.

We have also added a function called os.renames which will allow you to change the name of that file.
Note: Look at the top of the code and notice I have added a new variable called Path2, what it will do is locate the variable Path and then change it to Path2.
(May 21, 2014 11:17 AM)ZXshockaXZ Wrote:  I believe you want "Python Tutorial - OS Module #2" to say number 3?

Looks great man. I'll bet you're helping a lot of people out. Keep up the HQ posts.

Edited the thread, thanks alot for the support

-Cyber Punk
(May 21, 2014 12:14 PM)dberube Wrote:  Oh big bang. Are you seriously going to create a thread for every python functions in the standard library?
Because that would mean LOTS of threads. You could even start a cloth factory!

Hahahah, I love reading posts for children. :)
(May 23, 2014 09:33 PM)deiski Wrote:  We tell him this every time and he doesn't listen.

HAHAHAHAHHAHHA Sorry Cyan master of hf, ahah dont tell me what to do.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Python] by Bass_ReevesAug 20, 2023 01:44 AM 9 632 Aug 20, 2023 01:44 AM
Last Post: Lucky4L
[C] by w3w3w3Aug 3, 2021 12:38 PM 1 328 Aug 3, 2021 12:38 PM
Last Post: SIM-5058597
[Python] by Magpi3Jun 6, 2019 04:56 AM 7 215 Jun 6, 2019 04:56 AM
Last Post: Deathbox