Trong bài viết này, Tin học của em sẽ cùng bạn tìm hiểu về quản lý file và thư mục bằng Python, cụ thể là việc là tạo thư mục, đổi tên thư mục, liệt kê các thư mục và làm việc với chúng.

Thư mục trong Python

Ở bài tìm hiểu trước, chúng ta đã làm quen với file và các thao tác làm việc với file trong Python. Ở đây bạn có thể hiểu đơn giản rằng thư mục là nơi chứa tất cả các file. Nên sắp xếp code cũng như file trong các thư mục khác nhau để dễ dàng quản lý mọi thứ.

Python cũng cung cấp rất nhiều phương thức để xử lý các hoạt động đa dạng liên quan tới thư mục. Module os có được xây dựng để cung cấp các phương thức giúp bạn tạo, xóa, và thay đổi các thư mục.

Hiển thị thư mục hiện tại

Phương thức getcwd() hiển thị thư mục đang làm việc hiện tại, trả về kết quả dưới dạng một chuỗi.

Chúng ta cũng có thể sử dụng phương thức getcwdb() để nhận về kết quả dưới dạng byte.

>>> import os

>>> os.getcwd()
'C:\\Program Files\\PyScripter'

>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'

Thay đổi thư mục hiện tại

Thư mục làm việc hiện tại có thể được thay đổi bằng phương thức chdir().

chdir() nhận một tham số là tên thư mục bạn muốn tới từ thư mục hiện tại. Có thể sử dụng cả dấu gạch chéo (/) hoặc dấu gạch chéo ngược (\) để tách các phần tử trong đường dẫn, nhưng tốt nhất vẫn nên sử dụng dấu gạch ngược (\).

>>> os.chdir('C:\\Python33')

>>> print(os.getcwd())
C:\Python33

Danh sách thư mục và file

Bạn có thể liệt kê tất cả các tệp và thư mục con bên trong một thư mục bằng cách sử dụng phương thức listdir().

Phương thức này nhận một đường dẫn và trả về danh sách thư mục con và các file trong đường dẫn đó.

Nếu không có đường dẫn nào được chỉ định, kết quả trả về sẽ truy xuất từ thư mục làm việc hiện tại.

>>> print(os.getcwd())
C:\Python33

>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']

>>> os.listdir('G:\\')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']

Tạo một thư mục mới

Để tạo các thư mục mới, bạn sử dụng phương thức mkdir() của Module os.

Bạn có thể chọn nơi chứa thư mục mới bằng cách ghi đầy đủ đường dẫn tới nơi muốn tạo. Nếu đường dẫn đầy đủ không được chỉ định, thư mục mới sẽ được tạo trong thư mục làm việc hiện tại.

>>> os.mkdir('test')

>>> os.listdir()
['test']

Đổi tên thư mục hoặc tên file

Bạn sử dụng phương thức rename() để đổi tên một thư mục hoặc một tập tin.

>>> os.listdir()
['test']

>>> os.rename('test','new_one')

>>> os.listdir()
['new_one']

Xóa bỏ thư mục hoặc file

Để gỡ bỏ một file, bạn sử dụng phương thức remove()

Tương tự nhưng để xóa toàn bộ thư mục, sử dụng rmdir()

>>> os.listdir()
['new_one', 'old.txt']

>>> os.remove('old.txt')
>>> os.listdir()
['new_one']

>>> os.rmdir('new_one')
>>> os.listdir()
[]

Lưu ý rằng phương thức rmdir() chỉ có thể xóa các thư mục rỗng.

Vậy để loại bỏ một thư mục không rỗng, chúng ta có thể sử dụng phương thức rmtree() bên trong module shutil.

>>> os.listdir()
['test']

>>> os.rmdir('test')
Traceback (most recent call last):
...
OSError: [WinError 145] The directory is not empty: 'test'

>>> import shutil

>>> shutil.rmtree('test')
>>> os.listdir()
[]

Vậy là bạn đã làm quen được những thao tác cơ bản nhất với thư mục rồi. Module os trong Python vẫn còn cung cấp rất nhiều các phương thức hữu ích khác để thực hiện các hoạt động với file và thư mục nữa. Bạn hãy theo dõi trong những bài học tiếp theo của Tin học của em nhé.

Chúc bạn học Python thật vui!

262 BÌNH LUẬN

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

  2. You really make it seem so easy with your
    presentation but I find this matter to be really something which I think
    I would never understand. It seems too complex and
    very broad for me. I’m looking forward for your next
    post, I will try to get the hang of it!

  3. Hi, I think your website might be having browser compatibility issues.
    When I look at your blog in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping.

    I just wanted to give you a quick heads up! Other then that,
    very good blog!

  4. Hello there! I know this is somewhat off topic but I
    was wondering if you knew where I could get a captcha plugin for my comment form?

    I’m using the same blog platform as yours and I’m having trouble finding one?
    Thanks a lot!

  5. Undeniably believe that which you stated. Your favorite reason appeared to be on the net the
    easiest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they plainly do not
    know about. You managed to hit the nail upon the top and also defined out the whole
    thing without having side-effects , people can take
    a signal. Will likely be back to get more. Thanks

  6. Great blog here! Also your site a lot up very fast! What web host
    are you the usage of? Can I get your associate link
    in your host? I desire my website loaded up as quickly as yours lol

  7. My family all the time say that I am wasting my time here at web, except I know I am
    getting know-how everyday by reading such fastidious articles or reviews.

  8. I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but certainly you are going to a famous
    blogger if you are not already 😉 Cheers!

  9. When someone writes an piece of writing he/she keeps
    the thought of a user in his/her brain that how a user can be aware
    of it. Thus that’s why this paragraph is great. Thanks!

  10. It’s the best time to make some plans for the future and it
    is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or
    advice. Perhaps you can write next articles referring to this article.
    I want to read more things about it!

  11. Excellent post. Keep posting such kind of info on your page.

    Im really impressed by it.
    Hi there, You’ve done an incredible job. I’ll definitely digg it and
    in my view suggest to my friends. I’m sure they will be benefited from this web site.

  12. I simply could not leave your site prior to suggesting that I extremely enjoyed the usual information an individual supply
    to your visitors? Is gonna be back continuously to inspect new
    posts

  13. Great website you have here but I was curious if you knew of any discussion boards that cover the same topics talked about here?
    I’d really love to be a part of group where I can get feedback from other experienced individuals that
    share the same interest. If you have any suggestions, please let me know.
    Many thanks!

  14. I don’t know whether it’s just me or if perhaps everyone else encountering issues
    with your site. It appears as though some of the text within your posts
    are running off the screen. Can somebody else please provide feedback and let
    me know if this is happening to them as well?
    This might be a issue with my internet browser because I’ve had this
    happen previously. Many thanks

  15. My spouse and I absolutely love your blog and find many of your
    post’s to be what precisely I’m looking for.
    can you offer guest writers to write content for you?
    I wouldn’t mind publishing a post or elaborating on most of the subjects you write in relation to here.

    Again, awesome site!

  16. Fantastic beat ! I wish to apprentice while you amend your
    site, how can i subscribe for a blog website?
    The account aided me a acceptable deal. I have been a little bit familiar of this your
    broadcast offered shiny clear idea

  17. Wow! This could be one particular of the most useful blogs We ave ever arrive across on this subject. Basically Excellent. I am also an expert in this topic so I can understand your effort.

  18. I know this if off topic but I’m looking
    into starting my own blog and was curious what all is
    needed to get set up? I’m assuming having a blog like
    yours would cost a pretty penny? I’m not very internet smart so
    I’m not 100% certain. Any suggestions or advice would be greatly appreciated.

    Thanks

  19. Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is great, as well as the content!. Thanks For Your article about sex.

  20. What as Happening i am new to this, I stumbled upon this I have found It absolutely helpful and it has aided me out loads. I hope to contribute & assist other users like its aided me. Great job.

  21. I absolutely love your site.. Pleasant colors & theme.
    Did you create this amazing site yourself? Please reply back as
    I’m wanting to create my own website and would like to know where you got this
    from or what the theme is called. Many thanks!

  22. I got this site from my buddy who told me on the topic of this website and now
    this time I am visiting this website and reading very informative content at this place.

  23. Terrific article! This is the kind of info that
    are supposed to be shared around the internet. Shame on the search engines for
    no longer positioning this put up higher! Come on over
    and discuss with my website . Thanks =)

  24. Do you have a spam issue on this website; I also am a blogger, and I was wanting to know your situation; many of us
    have developed some nice methods and we are looking to exchange techniques with other
    folks, be sure to shoot me an email if interested.

  25. This is very interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your excellent post. Also, I have shared your website in my social networks!

  26. Pretty element of content. I simply stumbled upon your weblog and in accession capital to claim that I get actually enjoyed account your weblog posts.
    Any way I will be subscribing in your feeds and
    even I achievement you get right of entry to persistently quickly.

  27. It’а†s really a nice and helpful piece of information. I’а†m satisfied that you just shared this helpful information with us. Please keep us informed like this. Thanks for sharing.

  28. Thank you, I have recently been looking for information about this topic for ages and yours is the best I have discovered till now. But, what about the conclusion? Are you sure about the source?

  29. Wow! This can be one particular of the most helpful blogs We ave ever arrive across on this subject. Basically Great. I am also a specialist in this topic so I can understand your hard work.

  30. Nice blog right here! Additionally your web site a lot up very fast! What web host are you the use of? Can I get your affiliate link on your host? I wish my site loaded up as quickly as yours lol

  31. Whoa! This blog looks just like my old one! It as on a totally different subject but it has pretty much the same layout and design. Superb choice of colors!

  32. It as not that I want to copy your web site, but I really like the design and style. Could you tell me which style are you using? Or was it especially designed?

  33. Usually I don at read post on blogs, however I wish to say that this write-up very pressured me to try and do it! Your writing style has been surprised me. Thanks, quite nice post.

  34. Keep up the excellent piece of work, I read few posts on this web site and I think that your web site is really interesting and contains circles of good information.

THOÁT KHỎI BÌNH LUẬN

Please enter your comment!
Please enter your name here