Các thao tác trên thư mục (directory) với Python

Đây là bài 41/54 bài của series môn học Ngôn ngữ lập trình Python

Khi có quá nhiều file trong một chương trình, chúng cần sắp xếp các file trong từng thư mục (directory) để dễ quản lý. Một thư mục có thể chứa các tập tin hoặc các thư mục con (subdirectory). Python cũng hỗ trợ module os để giúp thao tác với thư mục, tập tin dễ dàng hơn.

1. Thư mục hiện hành (current directory) trong Python

1.1. Lấy đường dẫn của current directory trong Python

Để lấy đường dẫn của thư mục hiện hành (current directory), chúng ta sử dụng hàm getcwd() trong module os. Hàm getcwd() sẽ trả về một string là đường dẫn của thư mục mà chúng ta đang làm việc trong đó.

import os
print("Path of current directory:", os.getcwd())
Kết quả
Path of current directory: C:\python-examples

Trong ví dụ trên, chúng ta đang làm việc với file code Python example.py nằm trong thư mục C:\python-examples.

1.2. Thay đổi current directory trong Python

Tùy vào yêu cầu chương trình, chúng ta có thể thay đổi current directory. Module os hỗ trợ hàm chdir() để làm việc này.

import os
print("Path of current directory:", os.getcwd())
# change current directory
os.chdir('C:\Python\Python310')
print("Path of new current directory:", os.getcwd())
Kết quả
Path of current directory: C:\python-examples
Path of new current directory: C:\Python\Python310

2. Lấy danh sách tập tin và thư mục con của một thư mục

Hàm listdir() giúp lấy danh sách tập tin và thư mục con của một thư mục được chỉ rõ đường dẫn. Nếu đường dẫn không được chỉ rõ thì listdir() sẽ lấy danh sách tập tin và thư mục con của current directory.

import os
print("List directories and files of Python310 folder:")
print(os.listdir('C:\Python\Python310'))
Kết quả
List directories and files of Python310 folder:
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python310.dll', 'pythonw.exe', 'Scripts', 'share', 'tcl', 'Tools', 'vcruntime140.dll', 'vcruntime140_1.dll']

Trong ví dụ trên, chúng ta lấy list directories và files của foler C:\Python\Python310. Còn đoạn code bên dưới sẽ list directories và files của current directory.

import os
# current directory is C:\python-examples
print("List directories and files of current directory:")
print(os.listdir())
Kết quả
List directories and files of current directory:
['data.txt', 'example.py', 'gochocit.txt', 'main.py', 'Robot', '__pycache__']

3. Tạo (create) một thư mục mới trong Python

Hàm mkdir() giúp tạo một thư mục mới với việc cung cấp đường dẫn đầy đủ (full path). Nếu không cung cấp full path thì thư mục mới sẽ được tạo trong current directory.

import os
# create folder hocit in current directory
os.mkdir('hocit')
# create folder hocit in C:\Python\Python310
os.mkdir('C:\Python\Python310\hocit')

4. Đổi tên (rename) thư mục hoặc file trong Python

Để đổi tên (rename) của một thư mục hoặc tập tin, chúng ta sử dụng hàm rename(). Hàm rename() có 2 tham số cơ bản. Tham số 1 là tên (hoặc đường dẫn) của folder hoặc file cũ. Tham số 2 là tên (hoặc đường dẫn) của folder hoặc file mới.

import os
# list directoris and file before rename()
print("List directoris and file before rename():")
print(os.listdir())
# rename folder
os.rename('hocit', 'datait')
# rename file
os.rename('gochocit.txt', 'data.txt')
# list directoris and file after rename()
print("List directoris and file after rename():")
print(os.listdir())
Kết quả
List directoris and file before rename(): 
['example.py', 'gochocit.txt', 'hocit']
List directoris and file after rename(): 
['data.txt', 'datait', 'example.py']

5. Xóa (delete) thư mục hoặc file trong Python

Một file có thể được xóa với hàm remove(). Còn một thư mục có thể xóa với hàm rmdir().

import os
# list directoris and file before remove
print("List directoris and file before remove:")
print(os.listdir())
# remove folder hocit
os.rmdir('hocit')
# list directoris and file after remove
print("List directoris and file after remove:")
print(os.listdir())
Kết quả
List directoris and file before remove:
['example.py', 'hocit']
List directoris and file after remove:
['example.py']

Hàm rmdir() chỉ có thể xóa những folder rỗng (empty folder).

Giả sử, chúng ta có folder hocit có chứa 1 file data.txt. Lúc này, sử dụng hàm rmdir() để xóa thì chương trình sẽ báo lỗi.

import os
print(os.listdir())
print(os.listdir('C:\python-examples\hocit'))
os.rmdir('hocit')
print(os.listdir())
Kết quả
['example.py', 'hocit']
['data.txt']
Traceback (most recent call last):
  File "c:\python-examples\example.py", line 4, in <module>
    os.rmdir('hocit')
OSError: [WinError 145] The directory is not empty: 'hocit'

Để xóa một folder không rỗng thì chúng ta sử dụng hàm rmtree() trong module shutil.

import os
import shutil
print(os.listdir())
print(os.listdir('C:\python-examples\hocit'))
shutil.rmtree('hocit')
print(os.listdir())
Kết quả
['example.py', 'hocit']
['data.txt']
['example.py']

5/5 - (1 bình chọn)
Bài trước và bài sau trong môn học<< Ghi (write), tạo (create) và xóa (delete) tập tin (file) với PythonĐọc (read) file XML với Python >>
Chia sẻ trên mạng xã hội:

Trả lời

Lưu ý:

1) Vui lòng bình luận bằng tiếng Việt có dấu.

2) Khuyến khích sử dụng tên thật và địa chỉ email chính xác.

3) Mọi bình luận trái quy định sẽ bị xóa bỏ.