Hướng dẫn can i use python to rename files? - tôi có thể sử dụng python để đổi tên tệp không?

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:

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

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

    os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    9
    os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    8
    os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    9

  3. Sử dụng phương thức đổi tên () của mô -đun HĐH

    Sử dụ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 để đổi tên tệp trong thư mục. Chuyển cả tên cũ và tên mới cho hàm
    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)
    1 để đổi tên tệp.

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

Hướng dẫn can i use python to rename files? - tôi có thể sử dụng python để đổi tên tệp không?
Trước khi đổi tên một tập tin

Sau khi đổi tên

Hướng dẫn can i use python to rename files? - tôi có thể sử dụng python để đổi tên tệp không?
Sau khi đổi tên một tập tin

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

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

  • 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)
    6: Đường dẫn cho tệp phải được đổ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)
    7: Đường dẫn đích cho tệp mới được đổ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)
    8: (tùy chọn) Thư mục tệp nguồ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)
    9: (tùy chọn) Thư mục tệp đích

Lưu ý: Nếu

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 đã tồn tại thì
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 exists
1 will be thrown in Windows and in the case of UNIX an
The file already exists
2 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 exists
4.

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.

  1. Sử dụng
    The file already exists
    5 trong điều kiện
    The file already exists
    6
  2. Viết đổi tên mã trong khối Excet Try-Except.

Ví dụ 1: Sử dụng

The file already exists
5

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

Hướng dẫn can i use python to rename files? - tôi có thể sử dụng python để đổi tên tệp không?
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
    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

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

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
0

Sau 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')
1

Sử 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
    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
  • 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
    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')
    5 của lớp
    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')
    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ệp
  • Cuối cùng, sử dụng
    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 để đổi tên một tên cũ có tên mới

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')
1

Sử 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)
5

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

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

Chức năng nào được sử dụng để đổi tên các tệp trong Python?

Đổi tên () Phương thức trong Python được sử dụng để đổi tên tệp hoặc thư mục. method in Python is used to rename a file or directory.

Bạn có thể tự động hóa các tệp đổi tên không?

Có nhiều công cụ có sẵn có thể đổi tên tệp;Tuy nhiên, Power Automate là một công cụ mạnh mẽ, miễn phí, mã thấp có thể được sử dụng để tự động hóa các tác vụ trong môi trường hoạt động bao gồm Windows, Microsoft 365 và Azure.Power Automate is a robust, free, low-code tool can be used to automate tasks in an operating environment comprised of Windows, Microsoft 365 and Azure.

Có cách nào nhanh chóng đổi tên các tệp không?

Bạn có thể nhấn và giữ phím CTRL và sau đó nhấp vào từng tệp để đổi tên.Hoặc bạn có thể chọn tệp đầu tiên, nhấn và giữ phím Shift, sau đó nhấp vào tệp cuối cùng để chọn một nhóm.press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.