How to copy, move, rename, delete files/folders in Python

python-copy-move-rename-delete-files-folders-feature-image

In this tutorial, we’re gonna look at way to copy, move, rename, and delete files/folders in Python using shutil module.

Related Posts:
How to read/write files in Python

Copy file/folder in Python

Copy file

We use shutil.copy(source, destination) to copy the file at source to destination folder.

*Notes:
– This function returns path of the copied file.
– If destination is a filename, it will be used as the new name of the copied file.

>>> import shutil
>>> shutil.copy('D:\\ozenero\\tutorials-list.txt', 'D:\\ozenero\\Basics\\')
'D:\\ozenero\\Basics\\tutorials-list.txt'

# destination is a filename
>>> shutil.copy('D:\\ozenero\\tutorials-list.txt', 'D:\\ozenero\\Basics\\tutorials.txt')
'D:\\ozenero\\Basics\\tutorials.txt'
Copy folder

We use shutil.copytree(source, destination) to copy entire folder (including all folders and files inside) at source to destination folder.

>>> import shutil
>>> shutil.copytree('D:\\Python Files', 'D:\\Python\\Basic Tutorials')
'D:\\Python\\Basic Tutorials'

*Notes:
– This function returns path of the copied folder.
– If destination folder already exists, the function will throw a FileExistsError error.

Move file/folder in Python

We use shutil.move(source, destination) to move file or folder (including all folders and files inside) at source to destination folder.

*Notes:
– This function returns path of new location.
– If destination is a filename or a folder that doesn’t exist, it will be used as the new name of the moved file/folder.
– If there is already a file/folder with the same filename in destination, it will throw an error.
Important: If we move a file to a folder that doesn’t exist, the file WILL be moved and renamed WITHOUT file extension.

>>> import shutil

# file
>>> shutil.move('D:\\tutorials-list.txt', 'D:\\ozenero')
'D:\\ozenero\\tutorials-list.txt'
# folder

>>> shutil.move('D:\\Basics', 'D:\\ozenero')
'D:\\ozenero\\Basics'

# move file and rename
>>> shutil.move('D:\\tutorials-list.txt', 'D:\\ozenero\\list.txt')
'D:\\ozenero\\list.txt'

# 'tutorials-list.txt' is already in 'D:\ozenero' folder
>>> shutil.move('D:\\tutorials-list.txt', 'D:\\ozenero')
# shutil.Error: Destination path 'D:\ozenero\tutorials-list.txt' already exists

# 'D:\ozenero\list' doesn't exist
>>> shutil.move('D:\\tutorials-list.txt', 'D:\\ozenero\\list')
'D:\\ozenero\\list'
# 'tutorials-list.txt' is changed to 'list' (file)

Rename file/folder in Python

We can use shutil.move(source, destination) with the source same as destination to rename the file or folder.

>>> import shutil

# rename file
>>> shutil.move('D:\\ozenero\\Basics\\tutorials.txt', 'D:\\ozenero\\Basics\\posts.txt')
'D:\\ozenero\\Basics\\posts.txt'

# rename folder
>>> shutil.move('D:\\ozenero\\Basic Tutorials', 'D:\\ozenero\\BasicTuts')
'D:\\ozenero\\BasicTuts'

Delete file/folder in Python

Permanent delete

We have 3 functions for specific cases:
os.unlink(path): delete file at path.
os.rmdir(path): delete folder (must be empty) at path.
shutil.rmtree(path): delete folder (including all files and folder inside) at path.

>>> import os
# delete file
>>> os.unlink('D:\\ozenero\\list.txt')

# delete empty folder
>>> os.rmdir('D:\\ozenero\\Basic Tutorials')
# not empty folder -> throw an error
>>> os.rmdir('D:\\ozenero\\BasicTuts')
Traceback (most recent call last):
  File "", line 1, in 
OSError: [WinError 145] The directory is not empty: 'D:\\ozenero\\BasicTuts'

# delete folder with files and subfolders inside
>>> import shutil
>>> shutil.rmtree('D:\\ozenero\\BasicTuts')
Safe delete

Instead of permanently deleting files/folders, we can use third-party send2trash module that will files or folders to trash or recycle bin.

At first, we need to install send2trash module, open cmd, then run:
pip install send2trash

Once the installation is successful, we can see send2trash folder at Python\Python[version]\Lib\site-packages.
Now we’re gonna import the module and use its send2trash() function:

>>> import send2trash
>>> send2trash.send2trash('D:\\ozenero\\tutorials-list.txt')

106 thoughts on “How to copy, move, rename, delete files/folders in Python”

  1. wonderful points altogether, you simply received a brand new reader. What may you recommend about your put up that you simply made a few days in the past? Any sure?

  2. I and my friends were actually looking at the excellent advice on your web site while at once I had an awful feeling I never expressed respect to the blog owner for those strategies. All of the ladies were for that reason very interested to learn all of them and already have in truth been loving these things. Appreciate your really being really thoughtful as well as for going for this form of decent information most people are really desirous to learn about. My honest apologies for not saying thanks to you sooner.

  3. I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this hike.

  4. Attrɑctіve part of content. I just stumbled upon your web site ɑnd in accession caρital to claim tһat I ɑcquire
    actually enjoyed account your blog posts. Any way I wilⅼ be subscribing on your feeds and evgen I
    success y᧐u get entгy to persistently fast.

  5. Thanks for your publication. What I want to say is that when looking for a good on the web electronics store, look for a web-site with entire information on key elements such as the privacy statement, safety details, payment methods, along with terms plus policies. Usually take time to look into the help plus FAQ areas to get a superior idea of the way the shop works, what they can perform for you, and exactly how you can maximize the features.

  6. An intriguing discussion is definitely worth comment.

    I do think that you ought to write more about this issue,
    it may not be a taboo subject but generally folks don’t talk about such issues.
    To the next! Many thanks!!

  7. hey there and thank you for your information – I have definitely picked up something
    new from right here. I did however expertise a few technical points
    using this site, since I experienced to reload the web site a lot of times previous to
    I could get it to load correctly. I had been wondering if your web host is OK?
    Not that I’m complaining, but sluggish loading instances times will very frequently affect your placement in google and can damage your
    quality score if advertising and marketing with Adwords.
    Anyway I’m adding this RSS to my e-mail and
    could look out for a lot more of your respective interesting content.
    Make sure you update this again very soon.

  8. You are so awesome! I do not suppose I have read through a single thing like
    this before. So good to discover someone with some unique thoughts on this
    subject. Seriously.. thanks for starting this up.
    This website is something that is required on the
    web, someone with some originality!

  9. I’m amazed, I have to admit. Rarely do I encounter a blog that’s both equally educative and engaging, and let me tell
    you, you’ve hit the nail on the head. The problem is an issue that not enough men and women are speaking intelligently about.

    I am very happy that I stumbled across this during my hunt for something regarding this.

  10. I’m now not positive where you’re getting your
    information, however great topic. I needs to spend some
    time studying more or figuring out more. Thank you for fantastic info
    I was searching for this info for my mission.

  11. Hey would you mind stating which blog platform you’re working with?
    I’m looking to start my own blog soon but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique.

    P.S Sorry for being off-topic but I had to ask!

  12. My spouse and I stumbled over here coming from a different web page and thought
    I might check things out. I like what I see so now i’m following you.
    Look forward to looking over your web page again.

  13. Magnificent goods from you, man. I’ve understand your stuff previous to and you’re simply too magnificent. I actually like what you’ve received here, really like what you are stating and the best way by which you assert it. You are making it enjoyable and you still care for to stay it smart. I can not wait to learn far more from you. This is actually a terrific web site.

  14. Hello! I could have sworn I’ve been to your blog before but after looking
    at many of the articles I realized it’s new to me.
    Anyhow, I’m definitely pleased I came across it and I’ll be bookmarking it and checking
    back regularly!

  15. Excellent beat ! I wish to apprentice at the same time as
    you amend your web site, how could i subscribe for a weblog website?
    The account helped me a appropriate deal. I had been a little bit
    familiar of this your broadcast offered shiny transparent concept

  16. Throughout this great pattern of things you get a B+ with regard to hard work. Exactly where you actually lost me personally ended up being in the details. You know, as the maxim goes, details make or break the argument.. And that could not be more true here. Having said that, allow me reveal to you just what did do the job. The writing is actually rather engaging and this is probably why I am making an effort in order to comment. I do not make it a regular habit of doing that. Secondly, despite the fact that I can easily notice a leaps in reasoning you come up with, I am not convinced of exactly how you appear to unite your ideas which inturn make the actual conclusion. For the moment I shall subscribe to your position but trust in the foreseeable future you connect your dots much better.

  17. Hi I am so delighted I found your webpage, I really found you by accident, while I was researching on Google for something else, Anyhow I am here now and would just like to say many thanks for a incredible post
    and a all round entertaining blog (I also love the theme/design), I don’t have time to go through it all at
    the minute but I have bookmarked it and also added in your RSS
    feeds, so when I have time I will be back to read much more,
    Please do keep up the great job.

  18. I’m not that much of a internet reader to be honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your site to come back in the future.
    Cheers

  19. You can definitely see your skills in the article you write.
    The sector hopes for more passionate writers such as
    you who aren’t afraid to say how they believe.

    At all times follow your heart.

  20. I’ve been browsing online more than 2 hours today, yet I
    never found any interesting article like yours.
    It is pretty worth enough for me. Personally, if all web owners and
    bloggers made good content as you did, the web will be much more
    useful than ever before.

  21. I think this is one of the most important information for me.
    And i’m glad reading your article. But should remark on few general things, The site style is wonderful, the articles is really
    great : D. Good job, cheers

  22. Hello! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing a few months
    of hard work due to no data backup. Do you have any methods to prevent hackers?

  23. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some
    time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your
    new updates.

  24. I got this web site from my friend who informed
    me on the topic of this web page and now this time I am visiting this web site and
    reading very informative articles at this place.

  25. I used to be recommended this web site via my cousin. I
    am no longer positive whether or not this submit is written by way of him as nobody else recognize such designated about my problem.
    You’re amazing! Thank you!

  26. We’re a group of volunteers and opening a new scheme in our community.

    Your site offered us with valuable information to
    work on. You have done a formidable job and our whole community
    will be grateful to you.

  27. Wow that was strange. I just wrote an very long comment but after
    I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyway, just wanted to
    say fantastic blog!

  28. I think this is one of the most vital info for me.

    And i’m glad reading your article. But wanna remark on few general things, The web
    site style is great, the articles is really nice : D. Good job, cheers

  29. I am extremely impressed with your writing
    skills as well as with the layout on your weblog.
    Is this a paid theme or did you customize it yourself?
    Either way keep up the nice quality writing, it is
    rare to see a great blog like this one these days.

  30. I am just commenting to make you understand what a incredible encounter my friend’s daughter undergone using your web page. She even learned plenty of pieces, not to mention what it’s like to have an amazing coaching character to make other folks without difficulty fully understand some problematic things. You really surpassed visitors’ expectations. Many thanks for supplying the helpful, trustworthy, informative and even fun tips on your topic to Tanya.

  31. I loved as much as you’ll receive carried out right here. The sketch is attractive, your
    authored material stylish. nonetheless, you command get bought an nervousness over that you wish be
    delivering the following. unwell unquestionably come more formerly again since exactly the
    same nearly very often inside case you shield this hike.

  32. Thanks for some other informative website. Where else could I get that kind of information written in such a
    perfect method? I have a undertaking that I am simply now working on, and I’ve been at
    the look out for such info.

  33. I’ve read several good stuff here. Definitely price bookmarking for revisiting.

    I surprise how a lot effort you put to make this sort of fantastic informative site.

  34. When someone writes an piece of writing he/she retains the
    idea of a user in his/her mind that how a user can understand it.
    Therefore that’s why this post is outstdanding. Thanks!

  35. I’m extremely impressed together with your writing talents as
    neatly as with the structure in your blog. Is that this a
    paid subject or did you customize it yourself?
    Either way keep up the excellent high quality writing, it’s uncommon to see a nice weblog like
    this one today..

  36. Having read this I believed it was extremely enlightening.
    I appreciate you finding the time and energy to put this content together.
    I once again find myself spending way too much time both reading and posting comments.
    But so what, it was still worth it!

  37. I think this is one of the most important info for me. And i’m glad reading your article.
    But wanna remark on some general things, The site style is
    great, the articles is really nice : D. Good job, cheers

  38. I like the helpful info you provide in your articles.

    I will bookmark your weblog and check again here
    regularly. I am quite certain I’ll learn a lot of new stuff right here!

    Best of luck for the next!

  39. I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish.
    nonetheless, you command get got an nervousness over that
    you wish be delivering the following. unwell unquestionably come more
    formerly again since exactly the same nearly very often inside
    case you shield this hike.

  40. Pretty section of content. I just stumbled upon your weblog and in accession capital to assert that I
    acquire actually enjoyed account your blog posts.
    Anyway I will be subscribing to your augment and even I achievement
    you access consistently rapidly.

  41. hello!,I lіke your writing very much! рercentage we keep up a
    cⲟrrespondence more about your articⅼe on AOL? I need an expert on this space to resoklve my problem.
    Maybe that’s you! Looіking forwɑrd to look yoս.

  42. Heya i’m for the first time here. I found this board
    and I find It really useful & it helped me out much. I
    hope to give something back and help others like you aided me.

  43. Nice post. I learn something totally new
    and challenging on blogs I stumbleupon on a daily basis.
    It’s always helpful to read articles from other authors and practice something from other web sites.

  44. Terrific work! That is the type of info that are meant
    to be shared across the net. Shame on the search engines for no
    longer positioning this submit higher! Come on over and talk over with my website .

    Thank you =)

  45. Hi i am kavin, its my first time to commenting anyplace,
    when i read this article i thought i could also create comment due
    to this good piece of writing.

  46. naturally like your web-site however you have to
    take a look at the spelling on quite a few of
    your posts. A number of them are rife with spelling problems and I find it very bothersome to inform
    the reality however I’ll certainly come back again.

  47. I think this is among the most significant
    information for me. And i’m glad reading your article. But should remark on some
    general things, The web site style is perfect, the articles is really nice
    : D. Good job, cheers

  48. We’re a group of volunteers and starting a new scheme in our community.

    Your site offered us with valuable info to work
    on. You have done a formidable job and our whole community will be thankful to you.

  49. I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get got an nervousness over that you wish be delivering the following.

    unwell unquestionably come further formerly again as exactly the same nearly
    a lot often inside case you shield this increase.

  50. Good day! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get
    my blog to rank for some targeted keywords but I’m not seeing very good results.
    If you know of any please share. Cheers!

  51. Having read this I believed it was very enlightening. I appreciate you taking the time and effort to put this content together.
    I once again find myself spending a lot of time
    both reading and posting comments. But so what, it was still worth it!

  52. Definitely believe that that you said. Your favorite reason seemed to be at the internet the easiest thing to understand
    of. I say to you, I certainly get irked even as other folks think about worries that
    they plainly don’t understand about. You controlled to hit the nail upon the top as well
    as defined out the entire thing without having side effect
    , other people could take a signal. Will probably be back to get more.
    Thank you

  53. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet
    my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience
    with something like this. Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to
    your new updates.

  54. I haven¡¦t checked in here for a while because I thought it was getting boring, but the last few posts are great quality so I guess I¡¦ll add you back to my everyday bloglist. You deserve it my friend 🙂

  55. I’m really enjoying the theme/design of your website. Do you ever run into any browser compatibility issues? A number of my blog readers have complained about my site not working correctly in Explorer but looks great in Safari. Do you have any recommendations to help fix this problem?

  56. Very great post. I simply stumbled upon your blog and wanted to mention that I’ve truly enjoyed surfing around your blog posts. After all I will be subscribing to your rss feed and I hope you write again very soon!

  57. Great post. I was checking constantly this weblog and I’m impressed! Extremely useful info particularly the final section 🙂 I deal with such information a lot. I was seeking this particular information for a long time. Thanks and best of luck.

Leave a Reply

Your email address will not be published. Required fields are marked *