Programming2020-04-132 min read
Cách sắp xếp các file trong một folder gọn gàng sử dụng python
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.
Nguyen Pham
•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ệ.
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
codeimport 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
Tags:#Programming#Python#Uncategorized#xăp xếp file