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. Nội dung chính - 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
- 1.2. Thay đổi current directory trong Python
- 2. Lấy danh sách tập tin và thư mục con của một thư mục
- 3. Tạo (create) một thư mục mới trong Python
- 4. Đổi tên (rename) thư mục hoặc file trong Python
- 5.
Xóa (delete) thư mục hoặc file trong Python
1. Thư mục hiện hành (current directory) trong Python1.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 PythonTù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ụcHà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 PythonHà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 PythonMộ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']
- Định nghĩa và gọi phương thức (method) trong Java
- Toán tử số học và toán tử quan hệ trong C++
- Chương trình tìm dãy số Fibonacci trong Java
- Toán tử logic, toán tử trên bit và toán tử gán trong C++
- Hàm uniqid() trong PHP
|