Trong hướng dẫn này, bạn sẽ học cách đổi tên các tệp và thư mục bằng Python.
Sau khi đọc bài viết này, bạn sẽ học: -: –
- Đổi tên một tệp bằng phương thức đổi tên []
- Đổi tên các tệp phù hợp với một mẫu
- Đổi tên tất cả các tệp trong một thư mục
- Chỉ đổi tên các tệp trong danh sách
- Đổi tên và di chuyển một tập tin
Các bước để đổi tên tệp trong Python
Để đổi tên một tệp, vui lòng làm theo các bước sau:
- Tìm đường dẫn của một tệp để đổi tên
Để đổi tên một tập tin, chúng tôi cần đường dẫn của nó. Đường dẫn là vị trí của tệp trên đĩa. Một đường dẫn tuyệt đối chứa danh sách thư mục hoàn chỉnh cần thiết để định vị tệp. Một đường dẫn tương đối chứa thư mục hiện tại và sau đó là tên tệp.
An absolute path contains the complete directory list required to locate the file.
A relative path contains the current directory and then the file name. - Quyết định một tên mới
Lưu tên cũ và một tên mới trong hai biến riêng biệt .________ 18
9os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
8os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
9os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
- Sử dụng phương thức đổi tên [] của mô -đun HĐH
Sử dụng phương thức
0 để đổi tên tệp trong thư mục. Chuyển cả tên cũ và tên mới cho hàmimport os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
1 để đổi tên tệp.import os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
Ví dụ: Đổi tên một tập tin bằng Python
Trong ví dụ này, chúng tôi đang đổi tên chi tiết về chi tiết.
import os
# Absolute path of a file
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# Renaming the file
os.rename[old_name, new_name]
Output::
Trước khi đổi tên
Sau khi đổi tên
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
0
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
Như được hiển thị trong ví dụ, chúng ta có thể đổi tên một tệp trong Python bằng phương thức ________ 23 [] có sẵn trong mô -đun HĐH. Mô -đun
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
4 cung cấp các chức năng để tương tác với các hệ điều hành. Mô -đun này thuộc các mô -đun tiện ích tiêu chuẩn Python.os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
Sau đây là các tham số mà chúng ta cần vượt qua cho phương thức
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
0
6: Đường dẫn cho tệp phải được đổi tênimport os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
7: Đường dẫn đích cho tệp mới được đổi tênimport os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
8: [tùy chọn] Thư mục tệp nguồnimport os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
9: [tùy chọn] Thư mục tệp đíchimport os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
Lưu ý: Nếu
7 đã tồn tại thì import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
The file already exists
1 sẽ được ném vào Windows và trong trường hợp UNIX, The file already exists
2 sẽ bị ném.: If the
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
7 already exists then the The file already exists1 will be thrown in Windows and in the case of UNIX an
The file already exists2 will be thrown.
Đổi tên một tệp sau khi kiểm tra xem nó có tồn tại không
Phương pháp
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
0 làm tăng FileexistSerror hoặc Oserror khi tên tệp đích đã tồn tại. Điều này có thể tránh được bằng cách gói mã của chúng tôi trong khối The file already exists4.
Sử dụng hàm ISFILE [‘Path,] trước khi đổi tên một tệp. Nó trả về đúng nếu tệp đích đã tồn tại.
Chúng ta có thể sử dụng hai cách tiếp cận sau đây để tiếp tục đổi tên bằng cách xóa tệp cũ hoặc dừng mà không đổi tên.
- Sử dụng
The file already exists
5 trong điều kiệnThe file already exists
6 - Viết đổi tên mã trong khối Excet Try-Except.
Ví dụ 1: Sử dụng
The file already exists5
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
Đầu ra
The file already exists
Ví dụ 2: cùng một mã có thể được bọc trong khối Excet Try-Except như dưới đây.: The same code could be wrapped in the try-except block as below.
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# enclosing inside try-except
try:
os.rename[old_name, new_name]
except FileExistsError:
print["File already Exists"]
print["Removing existing file"]
# skip the below code
# if you don't' want to forcefully rename
os.remove[new_name]
# rename it
os.rename[old_name, new_name]
print['Done renaming a file']
Output::
File already Exists Removing existing file Done renaming a file
Đổi tên nhiều tệp trong Python
Đôi khi chúng ta cần đổi tên tất cả các tệp từ một thư mục. Hãy xem xét một thư mục có bốn tệp có tên khác nhau và chúng tôi muốn đổi tên tất cả các tên tệp.rename all files from a directory. Consider a folder with four files with different names, and we wanted to rename all file names.
Chúng tôi có thể đổi tên nhiều tệp trong một thư mục bằng phương thức
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
if os.path.isfile[new_name]:
print["The file already exists"]
else:
# Rename the file
os.rename[old_name, new_name]
0 bằng cách làm theo các bước dưới đây.- Nhận danh sách các tệp trong một thư mục bằng
The file already exists
9. Nó trả về một danh sách chứa tên của các mục trong thư mục đã cho. - Lặp lại trong danh sách bằng cách sử dụng một vòng lặp để truy cập từng tệp một
- Đổi tên từng tệp
Ví dụ sau đây cho thấy cách thay đổi tên của tất cả các tệp từ một thư mục.
import os
folder = r'E:\demos\files\reports\\'
count = 1
# count increase by 1 in each iteration
# iterate all files from a directory
for file_name in os.listdir[folder]:
# Construct old file name
source = folder + file_name
# Adding the count to the new file name and extension
destination = folder + "sales_" + str[count] + ".txt"
# Renaming the file
os.rename[source, destination]
count += 1
print['All Files Renamed']
print['New Names are']
# verify the result
res = os.listdir[folder]
print[res]
Đầu ra
All Files Renamed New Names are ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
Đổi tên nhiều tệp trong Python
Đôi khi chúng ta cần đổi tên tất cả các tệp từ một thư mục. Hãy xem xét một thư mục có bốn tệp có tên khác nhau và chúng tôi muốn đổi tên tất cả các tên tệp.
- Chúng tôi có thể đổi tên nhiều tệp trong một thư mục bằng phương thức
0 bằng cách làm theo các bước dưới đây.import os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
- Nhận danh sách các tệp trong một thư mục bằng
The file already exists
9. Nó trả về một danh sách chứa tên của các mục trong thư mục đã cho. - Lặp lại trong danh sách bằng cách sử dụng một vòng lặp để truy cập từng tệp một
- Đổi tên từng tệp
Example::
import os
files_to_rename = ['sales_1.txt', 'sales_4.txt']
folder = r"E:\demos\files\reports\\"
# Iterate through the folder
for file in os.listdir[folder]:
# Checking if the file is present in the list
if file in files_to_rename:
# construct current name using file name and path
old_name = os.path.join[folder, file]
# get file name without extension
only_name = os.path.splitext[file][0]
# Adding the new name with extension
new_base = only_name + '_new' + '.txt'
# construct full file path
new_name = os.path.join[folder, new_base]
# Renaming the file
os.rename[old_name, new_name]
# verify the result
res = os.listdir[folder]
print[res]
Đầu ra
['sales_1_new.txt', 'sales_2.txt', 'sales_3.txt', 'sales_4_new.txt']
Ví dụ 2: cùng một mã có thể được bọc trong khối Excet Try-Except như dưới đây.
Đổi tên nhiều tệp trong Python
Đôi khi chúng ta cần đổi tên tất cả các tệp từ một thư mục. Hãy xem xét một thư mục có bốn tệp có tên khác nhau và chúng tôi muốn đổi tên tất cả các tên tệp.
- Chúng tôi có thể đổi tên nhiều tệp trong một thư mục bằng phương thức
0 bằng cách làm theo các bước dưới đây.import os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
- Nhận danh sách các tệp trong một thư mục bằng
The file already exists
9. Nó trả về một danh sách chứa tên của các mục trong thư mục đã cho. - Lặp lại trong danh sách bằng cách sử dụng một vòng lặp để truy cập từng tệp một
- Đổi tên từng tệp
Ví dụ sau đây cho thấy cách thay đổi tên của tất cả các tệp từ một thư mục.
os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
0Sau khi đổi tên tất cả các tệp
Đổi tên chỉ một danh sách các tệp trong thư mục
Việc khớp mẫu được thực hiện bằng cách sử dụng mô -đun GLOB. Mô -đun GLOB được sử dụng để tìm các tệp và thư mục có tên theo một mẫu cụ thể.
Chúng ta có thể đổi tên các tệp khớp với một mẫu bằng các bước sau: -
- Viết một mẫu bằng cách sử dụng ký tự đại diện
- Sử dụng một phương thức glob [] để tìm danh sách các tệp phù hợp với một mẫu.
- Lặp lại thông qua các tệp trong thư mục
- Thay đổi tên theo quy ước đặt tên mới.
Ví dụ: Đổi tên tất cả các tệp văn bản bắt đầu với từ Sales Sales Bán hàng bên trong thư mục Báo cáo trên mạng với tên mới là doanh thu và một bộ đếm.: Rename all text files starting with the word “sales” inside the “reports” folder with the new name “revenue” and a counter.
os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
1Đầu ra
os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
2Đổi tên phần mở rộng của các tệp
Chúng ta chỉ có thể thay đổi phần mở rộng của các tệp bằng phương thức
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# enclosing inside try-except
try:
os.rename[old_name, new_name]
except FileExistsError:
print["File already Exists"]
print["Removing existing file"]
# skip the below code
# if you don't' want to forcefully rename
os.remove[new_name]
# rename it
os.rename[old_name, new_name]
print['Done renaming a file']
1. Điều này được thực hiện bằng cách lấy danh sách các tệp và sau đó chỉ nhận tên tệp bằng phương thức splitExt [] của mô -đun HĐH.Phương thức này trả về rễ và phần mở rộng riêng biệt. Khi chúng ta nhận được gốc/cơ sở của tên tệp, chúng ta có thể thêm tiện ích mở rộng mới vào nó trong khi đổi tên nó bằng phương thức
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# enclosing inside try-except
try:
os.rename[old_name, new_name]
except FileExistsError:
print["File already Exists"]
print["Removing existing file"]
# skip the below code
# if you don't' want to forcefully rename
os.remove[new_name]
# rename it
os.rename[old_name, new_name]
print['Done renaming a file']
1Sử dụng các bước dưới đây để đổi tên chỉ tiện ích mở rộng: -
- Nhận tên tệp danh sách từ một thư mục bằng cách sử dụng
3import os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" # enclosing inside try-except try: os.rename[old_name, new_name] except FileExistsError: print["File already Exists"] print["Removing existing file"] # skip the below code # if you don't' want to forcefully rename os.remove[new_name] # rename it os.rename[old_name, new_name] print['Done renaming a file']
- Tiếp theo, lặp lại từng tệp từ một danh sách tên tệp
- Xây dựng tên tệp hiện tại bằng phương thức ____44 bằng cách chuyển tên tệp và đường dẫn
- Bây giờ, hãy sử dụng phương thức
5 của lớpimport os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" # enclosing inside try-except try: os.rename[old_name, new_name] except FileExistsError: print["File already Exists"] print["Removing existing file"] # skip the below code # if you don't' want to forcefully rename os.remove[new_name] # rename it os.rename[old_name, new_name] print['Done renaming a file']
6 để thay thế tiện ích mở rộng hiện có bằng tiện ích mở rộng mới trong tên tệpimport os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" # enclosing inside try-except try: os.rename[old_name, new_name] except FileExistsError: print["File already Exists"] print["Removing existing file"] # skip the below code # if you don't' want to forcefully rename os.remove[new_name] # rename it os.rename[old_name, new_name] print['Done renaming a file']
- Cuối cùng, sử dụng
0 để đổi tên một tên cũ có tên mớiimport os old_name = r"E:\demos\files\reports\details.txt" new_name = r"E:\demos\files\reports\new_details.txt" if os.path.isfile[new_name]: print["The file already exists"] else: # Rename the file os.rename[old_name, new_name]
Hãy cùng xem ví dụ.
os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
3Đầu ra
os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
4Đổi tên phần mở rộng của các tệp
Chúng ta chỉ có thể thay đổi phần mở rộng của các tệp bằng phương thức
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# enclosing inside try-except
try:
os.rename[old_name, new_name]
except FileExistsError:
print["File already Exists"]
print["Removing existing file"]
# skip the below code
# if you don't' want to forcefully rename
os.remove[new_name]
# rename it
os.rename[old_name, new_name]
print['Done renaming a file']
1. Điều này được thực hiện bằng cách lấy danh sách các tệp và sau đó chỉ nhận tên tệp bằng phương thức splitExt [] của mô -đun HĐH.Phương thức này trả về rễ và phần mở rộng riêng biệt. Khi chúng ta nhận được gốc/cơ sở của tên tệp, chúng ta có thể thêm tiện ích mở rộng mới vào nó trong khi đổi tên nó bằng phương thức
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# enclosing inside try-except
try:
os.rename[old_name, new_name]
except FileExistsError:
print["File already Exists"]
print["Removing existing file"]
# skip the below code
# if you don't' want to forcefully rename
os.remove[new_name]
# rename it
os.rename[old_name, new_name]
print['Done renaming a file']
1Sử dụng các bước dưới đây để đổi tên chỉ tiện ích mở rộng: -
os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
5Nhận tên tệp danh sách từ một thư mục bằng cách sử dụng import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# enclosing inside try-except
try:
os.rename[old_name, new_name]
except FileExistsError:
print["File already Exists"]
print["Removing existing file"]
# skip the below code
# if you don't' want to forcefully rename
os.remove[new_name]
# rename it
os.rename[old_name, new_name]
print['Done renaming a file']
3
import os
old_name = r"E:\demos\files\reports\details.txt"
new_name = r"E:\demos\files\reports\new_details.txt"
# enclosing inside try-except
try:
os.rename[old_name, new_name]
except FileExistsError:
print["File already Exists"]
print["Removing existing file"]
# skip the below code
# if you don't' want to forcefully rename
os.remove[new_name]
# rename it
os.rename[old_name, new_name]
print['Done renaming a file']
Tiếp theo, lặp lại từng tệp từ một danh sách tên tệp
os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
6Đầu ra
os.rename[src, dst, *, src_dir_fd=None, dst_dir_fd=None]
7Đổi tên phần mở rộng của các tệp