Move a file trong Python là quá trình di chuyển file từ vị trí hiện tại của nó đến một vị trí khác trên hệ thống file. Có thể thực hiện bằng cách sử dụng module shutil
hoặc module os
.
Ví dụ:
Di chuyển file từ thư mục hiện tại đến một thư mục khác trên hệ thống:
import shutil
shutil.move('file.txt', '/path/to/new/folder/')
Thay đổi tên của file và di chuyển nó đến một thư mục khác:
import shutil
shutil.move('old_name.txt', '/path/to/new/folder/new_name.txt')
Di chuyển nhiều file đến thư mục đích:
import shutil
files_to_move = ['file1.txt', 'file2.txt', 'file3.txt']
destination_folder = '/path/to/new/folder/'
for file in files_to_move:
shutil.move(file, destination_folder)
Trong môi trường Linux, ta có thể sử dụng module shutil
trong Python để di chuyển một file. Dưới đây là ví dụ di chuyển một file từ thư mục hiện tại vào một thư mục mới được tạo ra tại đường dẫn /home/user/new_directory
:
import shutil
# Đường dẫn đến file cần di chuyển
source_file = "file.txt"
# Đường dẫn đến thư mục mới
destination_folder = "/home/user/new_directory"
# Di chuyển file
shutil.move(source_file, destination_folder)
Trong ví dụ này, ta sử dụng hàm move()
trong module shutil
để di chuyển file file.txt
từ thư mục hiện tại đến thư mục mới new_directory
được tạo ra tại đường dẫn /home/user
. Nếu file đã tồn tại trong thư mục đích, nó sẽ bị ghi đè. Nếu thư mục đích không tồn tại, nó sẽ được tạo mới.
Để di chuyển hoặc đổi tên một file trong Python mà không sử dụng shutil
, bạn có thể sử dụng module os
. Các hàm os.rename()
và os.replace()
có thể được sử dụng để thực hiện các tác vụ tương tự như các hàm shutil.move()
và shutil.copy()
.
Ví dụ:
- Đổi tên một file từ “file1.txt” sang “file2.txt”:
import os
os.rename("file1.txt", "file2.txt")
Di chuyển một file từ thư mục hiện tại sang thư mục mới:
import os
os.rename("file1.txt", "/path/to/new/directory/file1.txt")
Đổi tên và ghi đè một file:
import os
os.replace("file1.txt", "file2.txt")
Lưu ý: Hàm os.replace()
có thể ghi đè lên các file đã tồn tại trong trường hợp tên file mới đã được sử dụng trước đó.