---
title: "Cách sắp xếp các file trong một folder gọn gàng sử dụng python"
description: "Bạn có một folder gồm nhiều file khác nhau và bạn cần xắp xếp chúng. Đây là một script đơn giản các bạn có thể tự sửa lại để xắp xếp theo ý muốn."
date: "2020-04-13"
author:
  name: "Nguyen Pham"
  role: "Xin chào. Mình thích lập trình và công nghệ. Đây là blog mình chia sẻ lại các kiến thức về lập trình, công nghệ."
  avatar: "http://0.gravatar.com/avatar/6fb61398e24046b34e13870dd6c357b9?s=128&d=mm&r=g"
category: "Programming"
tags: ["Programming", "Python", "Uncategorized", "xăp xếp file"]
coverImage: "/blog/covers/cach-sap-xep-cac-file-trong-mot-folder-gon-gang-su-dung-python.png"
featured: false
readingTime: "2 min read"
---

Thư viện sử dụng

- os
- shutil

Giải thích

***os.listdir()***// liệt kê các folder va file ở nơi file python tồn tại

***os.getcwd()***// lấy đường dẫn file hiện tại

***os.mkdir()*** //tạo folder mới

***os.path.join(path,\*arg)***//nối đường dẫn

***os.path.exists(path)*** // Kiểm tra folder tồn tại hay không đúng trả về True

***os.path.isfile(path)*** // Kiểm tra có phải là một file hay folder

***shutil.move(old path,new path)*** //di chuyển file

```
import os
import shutil
#Loc cac tep
list=os.listdir()
Compressed=('zip','rar')
Documents=()
Picture=('jpg','PNG')
Programs=('exe')
Video=('mp4')
Music=('mp3','flac')
#cac folder
listdir=('Picture','Documents','Programs','Video','Music','Compressed')

for i in listdir:
    if(os.path.exists(os.path.join(os.getcwd(), i))):
        pass
    else:
        os.mkdir(os.path.join(os.getcwd(), i))
#loc file
for i in list:
    if (os.path.isfile(os.path.join(os.getcwd(), i))):
        a=i.split('.')
        if(a[len(a)-1] in Picture):
            try:
                shutil.move(os.path.join(os.getcwd(), i), os.path.join(os.getcwd(), 'Picture',i))
            finally:
                pass
        if (a[len(a) - 1] in Documents):
            try:
                shutil.move(os.path.join(os.getcwd(), i), os.path.join(os.getcwd(), 'Documents', i))
            finally:
                pass
        if (a[len(a) - 1] in Programs):
            try:
                shutil.move(os.path.join(os.getcwd(), i), os.path.join(os.getcwd(), 'Programs', i))
            finally:
                pass
        if (a[len(a) - 1] in Video):
            try:
                shutil.move(os.path.join(os.getcwd(), i), os.path.join(os.getcwd(), 'Video', i))
            finally:
                pass
        if (a[len(a) - 1] in Compressed):
            try:
                shutil.move(os.path.join(os.getcwd(), i), os.path.join(os.getcwd(), 'Compressed', i))
            finally:
                pass
        if (a[len(a) - 1] in Music):
            try:
                shutil.move(os.path.join(os.getcwd(), i), os.path.join(os.getcwd(), 'music', i))
            finally:
                pass
```
