Hướng dẫn how do you rename all files in python? - làm cách nào để đổi tên tất cả các tệp trong python?

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc OS module in Python
    In Python3, rename() method is used to rename a file or directory. This method is a part of the os module and comes in extremely handy. 
     

    Bàn luận

    Điều kiện tiên quyết: Mô -đun HĐH trong pythonin python3, đổi tên () phương thức được sử dụng để đổi tên tệp hoặc thư mục. Phương pháp này là một phần của mô -đun HĐH và có cực kỳ tiện dụng. & Nbsp; & nbsp; src is source address of file to be renamed and dst is destination with the new name.

    Cú pháp cho Os.rename ():

    Hướng dẫn how do you rename all files in python? - làm cách nào để đổi tên tất cả các tệp trong python?

    OS.RENAME (SRC, DST): SRC là địa chỉ nguồn của tệp để được đổi tên và DST là điểm đến với tên mới.
     

    Bây giờ nói cho n hình ảnh trong một thư mục có tên ngẫu nhiên. Ví dụ, hãy xem xét hình ảnh dưới đây:listdir method lists out all the content of a given directory.

    Bây giờ yêu cầu là đổi tên chúng theo thứ tự thời trang như Hostel1, Hostel2, Mạnh, v.v. Thực hiện điều này theo cách thủ công sẽ là một nhiệm vụ tẻ nhạt nhưng mục tiêu này có thể đạt được bằng cách sử dụng các phương thức đổi tên () và listDIR () trong mô -đun HĐH. & NBSP; 

    Phương thức listDIR liệt kê tất cả nội dung của một thư mục nhất định. where src is the source folder to be listed out.

    Cú pháp cho ListDir (): & nbsp;

    Danh sách = OS.ListDir (‘SRC,): Trong đó SRC là thư mục nguồn được liệt kê.os.rename(src,dst) is “folder_name/file_name”.
      
    Below is the implementation : 

    Python3

    Mã sau đây sẽ làm công việc cho chúng tôi. Nó đi qua danh sách tất cả các hình ảnh trong thư mục XYZ, xác định địa chỉ đích (DST) và Nguồn (SRC) và đổi tên bằng mô -đun đổi tên. & NBSP;

    Định dạng được chấp nhận cho các địa chỉ đích (DST) và nguồn (SRC) được đưa ra dưới dạng đối số trong OS.RENAME (SRC, DST) là thư mục_name/file_name.

    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

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

    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)
    2
    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)
    3
    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
    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)
    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)
    2
    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
    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
    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
    The file already exists
    0
    The file already exists
    1

    The file already exists
    2
    The file already exists
    3
    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
    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"
    
    # 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

    The file already exists
    2
    The file already exists
    3
    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
    The file already exists
    5
    The file already exists
    6

    ________ 32 ________ 38 ________ 24 ________ 35 ________ 41 & nbsp;

    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)
    2
    File already Exists
    Removing existing file
    Done renaming a file
    6

    The file already exists
    2
    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')
    8

    The output of this code will look something like this – 
     

    Hướng dẫn how do you rename all files in python? - làm cách nào để đổi tên tất cả các tệp trong python?

    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')
    9
    File already Exists
    Removing existing file
    Done renaming a file
    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)
    4
    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
    File already Exists
    Removing existing file
    Done renaming a file
    3
    File already Exists
    Removing existing file
    Done renaming a file
    4
    This code may not run in online IDE, since it use external image file directory.
     

    Vấn đề thực hành: Đổi tên một tệp hình ảnh

    Chúng tôi có thể đổi tên bất kỳ tệp nào trong một thư mục và các tệp thuộc bất kỳ loại nào bằng cách sử dụng

    File already Exists
    Removing existing file
    Done renaming a file
    9. Trong ví dụ dưới đây, chúng tôi sẽ thay đổi tên của một tệp hình ảnh bên trong thư mục.: –

    • os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
      6
    • Trong bài viết này, chúng tôi đã đề cập đến những điều cơ bản của việc đổi tên một tập tin, phương thức được sử dụng để đổi tên. Chúng tôi cũng đã thấy cách đổi tên một tệp với một mẫu cụ thể, đặt tên tất cả các tệp trong một thư mục và thêm một ngày vào tệp. Chúng tôi cũng với ví dụ làm thế nào để thay đổi phần mở rộng của tệp và cách di chuyển một tệp đến một vị trí mới sau khi thay đổi tên.
    • Làm thế nào để bạn đổi tên một tập tin trong Python?
    • Đổi tên nhiều tập tin trong Python.
    • Nhận danh sách các tệp trong một thư mục bằng hệ điều hành. listDir (). 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 ..

    1. Làm cách nào để đổi tên tất cả các tệp cùng một lúc?

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

      File already Exists
      Removing existing file
      Done renaming a file
      7
      File already Exists
      Removing existing file
      Done renaming a file
      8

    3. Có cách nào để thay đổi nhiều tên tệp cùng một lúc không?

      Cách đổi tên hàng loạt nhiều tệp trong Windows: Đổi tên các tệp riêng lẻ.

    Nhấp chuột phải vào tệp đầu tiên trong thư mục, sau đó nhấp vào Đổi tên. ....

    Nhập tên mới cho tệp, sau đó nhấn phím tab trên bàn phím của bạn. ....

    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 how do you rename all files in python? - làm cách nào để đổi tên tất cả các tệp trong python?
    Trước khi đổi tên một tập tin

    Sau khi đổi tên

    Hướng dẫn how do you rename all files in python? - làm cách nào để đổi tên tất cả các tệp trong python?
    Sau khi đổi tên một tập tin

    File already Exists Removing existing file Done renaming a file9

    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 ________ 62 () có sẵn trong mô -đun HĐH. Mô -đun

    os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    9 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

    File already Exists
    Removing existing file
    Done renaming a file
    9

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

    Lưu ý: Nếu

    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)
    6 đã tồn tại thì
    All Files Renamed
    New Names are
    ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
    0 sẽ được ném vào Windows và trong trường hợp UNIX,
    All Files Renamed
    New Names are
    ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
    1 sẽ bị ném.
    : If the
    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)
    6 already exists then the
    All Files Renamed
    New Names are
    ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
    0 will be thrown in Windows and in the case of UNIX an
    All Files Renamed
    New Names are
    ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
    1 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 thức

    File already Exists
    Removing existing file
    Done renaming a file
    9 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
    All Files Renamed
    New Names are
    ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
    3.

    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
      All Files Renamed
      New Names are
      ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
      4 trong điều kiện
      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')
      9
    2. Viết đổi tên mã trong khối Excet Try-Except.

    Ví dụ 1: Sử dụng

    All Files Renamed
    New Names are
    ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
    4

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

    Đầu ra::

    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

    File already Exists
    Removing existing file
    Done renaming a file
    9 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
      All Files Renamed
      New Names are
      ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
      8. 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 how do you rename all files in python? - làm cách nào để đổi tên tất cả các tệp trong python?
    Ví dụ 2: cùng một mã có thể được bọc trong khối Excet Try-Except như dưới đây.

    Đầu ra:

    Đổ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
      File already Exists
      Removing existing file
      Done renaming a file
      9 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
      All Files Renamed
      New Names are
      ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
      8. 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

    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.

    Đầu ra:

    Đổ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
      File already Exists
      Removing existing file
      Done renaming a file
      9 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
      All Files Renamed
      New Names are
      ['sales_0.txt', 'sales_1.txt', 'sales_2.txt', 'sales_3.txt']
      8. 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

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

    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.

    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

    Trong khi đổi tên các tệp bên trong một thư mục, đôi khi chúng ta có thể chỉ cần đổi tên một danh sách các tệp, không phải tất cả các tệp. Sau đây là các bước chúng tôi cần tuân theo để chỉ đổi tên một tập hợp các tệp bên trong một thư mục.

    • Cung cấp danh sách các tệp cần được đổi tên
    • Lặp lại qua danh sách các tệp trong thư mục chứa các tệp
    • Kiểm tra xem tệp có mặt trong danh sách không
    • Nếu có mặt, đổi tên tệp theo quy ước mong muốn. Khác, chuyển sang tệp tiếp theo

    Đổi tên các tệp bằng dấu thời gian: 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

    Ví dụ 2: cùng một mã có thể được bọc trong khối Excet Try-Except như dưới đây.

    Đầu ra:

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

    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
      
      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)
      
      2
    • 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 ____83 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
      
      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)
      
      4 của lớp
      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)
      
      5 để 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
      File already Exists
      Removing existing file
      Done renaming a file
      9 để đổ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 và sau đó di chuyển một tập tin đến một vị trí mới

    Với sự trợ giúp của phương thức

    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)
    
    0, chúng tôi có thể đổi tên một tệp và sau đó di chuyển nó đến một vị trí mới. Điều này được thực hiện bằng cách chuyển vị trí mới cho tham số
    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)
    
    0
    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)
    6.

    Hãy xem xét ví dụ dưới đây nơi chúng tôi đang xác định hai thư mục khác nhau là nguồn và đích riêng biệt. Sau đó, sử dụng

    ['sales_1_new.txt', 'sales_2.txt', 'sales_3.txt', 'sales_4_new.txt']
    0, chúng tôi đang thay đổi tên và vị trí của tệp.

    Cuối cùng khi chúng tôi in các tệp ở vị trí mới, chúng tôi có thể thấy tệp trong danh sách.

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

    Vấn đề thực hành: Đổi tên một tệp hình ảnh

    Chúng tôi có thể đổi tên bất kỳ tệp nào trong một thư mục và các tệp thuộc bất kỳ loại nào bằng cách sử dụng

    File already Exists
    Removing existing file
    Done renaming a file
    9. Trong ví dụ dưới đây, chúng tôi sẽ thay đổi tên của một tệp hình ảnh bên trong thư mục.

    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 và sau đó di chuyển một tập tin đến một vị trí mới

    Làm thế nào để bạn đổi tên một tập tin trong Python?

    Đổi tên nhiều tập tin trong Python..
    Nhận danh sách các tệp trong một thư mục bằng hệ điều hành. listDir (). 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 ..

    Làm cách nào để đổi tên tất cả các tệp cùng một lúc?

    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.

    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.

    Có cách nào để thay đổi nhiều tên tệp cùng một lúc không?

    Cách đổi tên hàng loạt nhiều tệp trong Windows: Đổi tên các tệp riêng lẻ..
    Nhấp chuột phải vào tệp đầu tiên trong thư mục, sau đó nhấp vào Đổi tên.....
    Nhập tên mới cho tệp, sau đó nhấn phím tab trên bàn phím của bạn.....
    Tiếp tục nhập tên tệp và nhấn tab để đạp sang tệp tiếp theo, cho đến khi tất cả các tệp của bạn được đổi tên ..