Hướng dẫn get current directory python

The pathlib module, introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths), makes the path-related experience much much better.

pwd

/home/skovorodkin/stack

tree

.
└── scripts
    ├── 1.py
    └── 2.py

In order to get the current working directory, use Path.cwd():

from pathlib import Path

print(Path.cwd())  # /home/skovorodkin/stack

To get an absolute path to your script file, use the Path.resolve() method:

print(Path(__file__).resolve())  # /home/skovorodkin/stack/scripts/1.py

And to get the path of a directory where your script is located, access .parent (it is recommended to call .resolve() before .parent):

print(Path(__file__).resolve().parent)  # /home/skovorodkin/stack/scripts

Remember that __file__ is not reliable in some situations: How do I get the path of the current executed file in Python?.


Please note, that Path.cwd(), Path.resolve() and other Path methods return path objects (PosixPath in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open built-in function could only work with string or bytes objects, and did not support Path objects, so you had to convert Path objects to strings or use the Path.open() method, but the latter option required you to change old code:

File scripts/2.py

from pathlib import Path

p = Path(__file__).resolve()

with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass

print('OK')

Output

python3.5 scripts/2.py

Traceback (most recent call last):
  File "scripts/2.py", line 11, in 
    with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')

As you can see, open(p) does not work with Python 3.5.

PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike objects to the open function, so now you can pass Path objects to the open function directly:

python3.6 scripts/2.py

OK

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 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 
    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