Hướng dẫn can you move files with python? - bạn có thể di chuyển tệp bằng python không?

Trong hướng dẫn Python này, bạn sẽ học cách di chuyển các tệp và thư mục từ vị trí này sang vị trí khác.

Sau khi đọc bài viết này, bạn sẽ học: -: –

  • Cách di chuyển các tệp đơn và nhiều tệp bằng cách sử dụng & nbsp; phương thức
    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    1
  • Di chuyển các tệp phù hợp với một mẫu [ký tự đại diện]
  • Di chuyển toàn bộ thư mục

Các bước để di chuyển một tệp trong Python

Mô-đun Python Shutil cung cấp một số chức năng để thực hiện các hoạt động cấp cao trên các tệp và bộ sưu tập tệp. Chúng ta có thể di chuyển các tệp bằng phương thức

import shutil

# absolute path
src_path = r"E:\pynative\reports\sales.txt"
dst_path = r"E:\pynative\account\sales.txt"
shutil.move[src_path, dst_path]
1. Các bước dưới đây cho thấy cách di chuyển một tệp từ thư mục này sang thư mục khác.

  1. Tìm đường dẫn của một tệp

    Chúng ta có thể di chuyển một tệp bằng cả đường dẫn tương đối và đường dẫn tuyệt đối. Đườ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. Ví dụ: & nbsp; ________ 13ales ________ 14 & nbsp; là một con đường tuyệt đối để khám phá Sales.txt.
    An absolute path contains the complete directory list required to locate the file. For example, 

    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    3ales
    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    4 is an absolute path to discover the sales.txt.

  2. Sử dụng hàm SOWL.MOVE []

    Hàm

    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    1 được sử dụng để di chuyển một tệp từ thư mục này sang thư mục khác.
    First, import the shutil module and Pass a source file path and destination directory path to the
    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    6 function.

  3. Sử dụng hàm Os.ListDir [] và SHOTIL Move [] để di chuyển tất cả các tệp

    Giả sử bạn muốn di chuyển tất cả/nhiều tệp từ thư mục này sang thư mục khác, sau đó sử dụng hàm

    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    7 để liệt kê tất cả các tệp của thư mục nguồn, sau đó lặp lại danh sách bằng cách sử dụng vòng lặp và di chuyển mỗi tệp bằng hàm
    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    8.

Ví dụ: Di chuyển một tệp duy nhất

Sử dụng phương thức SOWL.MOVE [] Di chuyển tệp vĩnh viễn từ thư mục này sang thư mục khác.

shutil.move[source, destination, copy_function = copy2]
  • import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    9: Đường dẫn của tệp nguồn cần được di chuyển.
  • import os
    import shutil
    
    src_folder = r"E:\pynative\reports\\"
    dst_folder = r"E:\pynative\account\\"
    file_name = 'sales.csv'
    
    # check if file exist in destination
    if os.path.exists[dst_folder + file_name]:
        # Split name and extension
        data = os.path.splitext[file_name]
        only_name = data[0]
        extension = data[1]
        # Adding the new name
        new_base = only_name + '_new' + extension
        # construct full file path
        new_name = os.path.join[dst_folder, new_base]
        # move file
        shutil.move[src_folder + file_name, new_name]
    else:
        shutil.move[src_folder + file_name, dst_folder + file_name]
    0: Đường dẫn của thư mục đích.
  • import os
    import shutil
    
    src_folder = r"E:\pynative\reports\\"
    dst_folder = r"E:\pynative\account\\"
    file_name = 'sales.csv'
    
    # check if file exist in destination
    if os.path.exists[dst_folder + file_name]:
        # Split name and extension
        data = os.path.splitext[file_name]
        only_name = data[0]
        extension = data[1]
        # Adding the new name
        new_base = only_name + '_new' + extension
        # construct full file path
        new_name = os.path.join[dst_folder, new_base]
        # move file
        shutil.move[src_folder + file_name, new_name]
    else:
        shutil.move[src_folder + file_name, dst_folder + file_name]
    1: Di chuyển tệp không là gì ngoài việc sao chép một tệp vào một vị trí mới và xóa cùng một tệp khỏi nguồn. Tham số này là hàm được sử dụng để sao chép tệp và giá trị mặc định của nó là
    import os
    import shutil
    
    src_folder = r"E:\pynative\reports\\"
    dst_folder = r"E:\pynative\account\\"
    file_name = 'sales.csv'
    
    # check if file exist in destination
    if os.path.exists[dst_folder + file_name]:
        # Split name and extension
        data = os.path.splitext[file_name]
        only_name = data[0]
        extension = data[1]
        # Adding the new name
        new_base = only_name + '_new' + extension
        # construct full file path
        new_name = os.path.join[dst_folder, new_base]
        # move file
        shutil.move[src_folder + file_name, new_name]
    else:
        shutil.move[src_folder + file_name, dst_folder + file_name]
    2. Đây có thể là bất kỳ chức năng nào khác như
    import os
    import shutil
    
    src_folder = r"E:\pynative\reports\\"
    dst_folder = r"E:\pynative\account\\"
    file_name = 'sales.csv'
    
    # check if file exist in destination
    if os.path.exists[dst_folder + file_name]:
        # Split name and extension
        data = os.path.splitext[file_name]
        only_name = data[0]
        extension = data[1]
        # Adding the new name
        new_base = only_name + '_new' + extension
        # construct full file path
        new_name = os.path.join[dst_folder, new_base]
        # move file
        shutil.move[src_folder + file_name, new_name]
    else:
        shutil.move[src_folder + file_name, dst_folder + file_name]
    3 hoặc
    import os
    import shutil
    
    src_folder = r"E:\pynative\reports\\"
    dst_folder = r"E:\pynative\account\\"
    file_name = 'sales.csv'
    
    # check if file exist in destination
    if os.path.exists[dst_folder + file_name]:
        # Split name and extension
        data = os.path.splitext[file_name]
        only_name = data[0]
        extension = data[1]
        # Adding the new name
        new_base = only_name + '_new' + extension
        # construct full file path
        new_name = os.path.join[dst_folder, new_base]
        # move file
        shutil.move[src_folder + file_name, new_name]
    else:
        shutil.move[src_folder + file_name, dst_folder + file_name]
    4.

Trong ví dụ này, chúng tôi đang chuyển tệp sales.txt từ thư mục báo cáo sang thư mục tài khoản.

import shutil

# absolute path
src_path = r"E:\pynative\reports\sales.txt"
dst_path = r"E:\pynative\account\sales.txt"
shutil.move[src_path, dst_path]

Note::

  • Hàm di chuyển [] trả về đường dẫn của tệp bạn đã di chuyển.
  • Nếu đường dẫn đích của bạn khớp với một tệp khác, tệp hiện tại sẽ bị ghi đè.
  • Nó sẽ tạo một thư mục mới nếu một đường dẫn đích được chỉ định không tồn tại trong khi di chuyển tệp.

Di chuyển tệp và đổi tên

Hãy để giả sử bạn muốn di chuyển một tệp, nhưng cùng một tên tệp đã tồn tại trong đường dẫn đích. Trong những trường hợp như vậy, bạn có thể chuyển tệp bằng cách đổi tên nó.

Hãy để xem cách di chuyển một tệp và thay đổi tên của nó.

  • Lưu trữ đường dẫn thư mục nguồn và đích vào hai biến riêng biệt
  • Lưu trữ tên tệp vào một biến khác
  • Kiểm tra xem tệp có tồn tại trong thư mục đích không
  • Nếu có, hãy xây dựng một tên mới cho một tệp và sau đó chuyển tên đó cho phương thức
    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    1.

Giả sử chúng tôi muốn chuyển sales.csv vào một thư mục được gọi vào tài khoản và nếu nó tồn tại, hãy đổi tên thành sales_new.csv và di chuyển nó.

import os
import shutil

src_folder = r"E:\pynative\reports\\"
dst_folder = r"E:\pynative\account\\"
file_name = 'sales.csv'

# check if file exist in destination
if os.path.exists[dst_folder + file_name]:
    # Split name and extension
    data = os.path.splitext[file_name]
    only_name = data[0]
    extension = data[1]
    # Adding the new name
    new_base = only_name + '_new' + extension
    # construct full file path
    new_name = os.path.join[dst_folder, new_base]
    # move file
    shutil.move[src_folder + file_name, new_name]
else:
    shutil.move[src_folder + file_name, dst_folder + file_name]

Di chuyển tất cả các tệp từ một thư mục

Đôi khi chúng tôi muốn di chuyển tất cả các tệp từ thư mục này sang thư mục khác. Thực hiện theo các bước dưới đây để di chuyển tất cả các tệp từ một thư mục.

  • Nhận danh sách tất cả các tệp có trong thư mục nguồn bằng & nbsp; ________ 17 & nbsp; function. Nó trả về a & nbsp; list & nbsp; chứa tên của các tệp và thư mục trong thư mục đã cho.
  • Lặp lại trong danh sách bằng cách sử dụng A & nbsp; cho Loop & nbsp; để lấy tên tệp riêng lẻ
  • Trong mỗi lần lặp, kết hợp tên tệp hiện tại với đường dẫn thư mục nguồn
  • Bây giờ sử dụng phương thức & nbsp; ________ 11 & nbsp; để di chuyển tệp hiện tại đến đường dẫn thư mục đích.

Ví dụ: Di chuyển tất cả các tệp từ thư mục báo cáo vào thư mục tài khoản.: Move all files from the report folder into a account folder.

import os
import shutil

source_folder = r"E:\pynative\reports\\"
destination_folder = r"E:\pynative\account\\"

# fetch all files
for file_name in os.listdir[source_folder]:
    # construct full file path
    source = source_folder + file_name
    destination = destination_folder + file_name
    # move only files
    if os.path.isfile[source]:
        shutil.move[source, destination]
        print['Moved:', file_name]

Mã của chúng tôi đã di chuyển hai tập tin. Dưới đây là danh sách các tệp trong thư mục đích:

  • profits.txt
  • revenue.txt
  • expense.txt

Sử dụng chức năng & nbsp; ____ 28 & nbsp; để liệt kê tất cả các tệp có trong thư mục đích để xác minh kết quả.

Di chuyển nhiều tập tin

Hãy giả sử bạn muốn chỉ di chuyển một vài tệp. Trong ví dụ này, chúng ta sẽ thấy cách di chuyển các tệp có trong danh sách từ một thư mục cụ thể vào thư mục đích.

import shutil

source_folder = r"E:\pynative\reports\\"
destination_folder = r"E:\pynative\account\\"
files_to_move = ['profit.csv', 'revenue.csv']

# iterate files
for file in files_to_move:
    # construct full file path
    source = source_folder + file
    destination = destination_folder + file
    # move file
    shutil.move[source, destination]
    print['Moved:', file]

Output::

Moved: profit.csv
Moved: revenue.csv

Di chuyển các tệp phù hợp với một mẫu [ký tự đại diện]

Giả sử, bạn muốn di chuyển các tệp nếu một tên chứa một chuỗi cụ thể.

& Nbsp; python glob & nbsp; mô -đun, một phần của thư viện tiêu chuẩn Python, được sử dụng để & nbsp; tìm các tệp và thư mục có tên theo một mẫu cụ thể.find the files and folders whose names follow a specific pattern.

glob.glob[pathname, *, recursive=False]
  • Chúng ta có thể sử dụng & nbsp; ký tự đại diện & nbsp; để khớp mẫu. Phương thức & nbsp;wildcard characters for pattern matching. The 
    import os
    import shutil
    
    src_folder = r"E:\pynative\reports\\"
    dst_folder = r"E:\pynative\account\\"
    file_name = 'sales.csv'
    
    # check if file exist in destination
    if os.path.exists[dst_folder + file_name]:
        # Split name and extension
        data = os.path.splitext[file_name]
        only_name = data[0]
        extension = data[1]
        # Adding the new name
        new_base = only_name + '_new' + extension
        # construct full file path
        new_name = os.path.join[dst_folder, new_base]
        # move file
        shutil.move[src_folder + file_name, new_name]
    else:
        shutil.move[src_folder + file_name, dst_folder + file_name]
    9 method returns a list of files or folders that matches the pattern specified in the 
    import os
    import shutil
    
    source_folder = r"E:\pynative\reports\\"
    destination_folder = r"E:\pynative\account\\"
    
    # fetch all files
    for file_name in os.listdir[source_folder]:
        # construct full file path
        source = source_folder + file_name
        destination = destination_folder + file_name
        # move only files
        if os.path.isfile[source]:
            shutil.move[source, destination]
            print['Moved:', file_name]
    0 argument.
  • Tiếp theo, sử dụng vòng lặp để di chuyển từng tệp bằng cách sử dụng
    import shutil
    
    # absolute path
    src_path = r"E:\pynative\reports\sales.txt"
    dst_path = r"E:\pynative\account\sales.txt"
    shutil.move[src_path, dst_path]
    1

Tham khảo điều này để sử dụng các ký tự đại diện khác nhau để xây dựng các mẫu khác nhau.

Di chuyển các tệp dựa trên tiện ích mở rộng tệp

Trong ví dụ này, chúng tôi sẽ di chuyển các tệp có phần mở rộng TXT.

import glob
import os
import shutil

src_folder = r"E:\pynative\report"
dst_folder = r"E:\pynative\account\\"

# Search files with .txt extension in source directory
pattern = "\*.txt"
files = glob.glob[src_folder + pattern]

# move the files with txt extension
for file in files:
    # extract file name form file path
    file_name = os.path.basename[file]
    shutil.move[file, dst_folder + file_name]
    print['Moved:', file]

Output::

Moved: E:\pynative\report\revenue.txt
Moved: E:\pynative\report\sales.txt

Di chuyển các tệp dựa trên tên tệp

Hãy để xem cách di chuyển một tệp có tên bắt đầu bằng một chuỗi cụ thể.

import glob
import os
import shutil

src_folder = r"E:\pynative\reports"
dst_folder = r"E:\pynative\account\\"

# move file whose name starts with string 'emp'
pattern = src_folder + "\emp*"
for file in glob.iglob[pattern, recursive=True]:
    # extract file name form file path
    file_name = os.path.basename[file]
    shutil.move[file, dst_folder + file_name]
    print['Moved:', file]

Output::

import shutil

# absolute path
src_path = r"E:\pynative\reports\sales.txt"
dst_path = r"E:\pynative\account\sales.txt"
shutil.move[src_path, dst_path]
0

Bài tập và câu đố Python

Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.

  • Hơn 15 bài tập và câu đố dành riêng cho chủ đềTopic-specific Exercises and Quizzes
  • Mỗi bài tập chứa 10 câu hỏi
  • Mỗi bài kiểm tra chứa 12-15 mcq

Làm cách nào để di chuyển một tệp cụ thể trong Python?

Các bước để di chuyển một tập tin trong Python..
Tìm đường dẫn của một tập tin. Chúng ta có thể di chuyển một tệp bằng cả đường dẫn tương đối và đường dẫn tuyệt đối. ....
Sử dụng hàm SOWL.MOVE []. Shutil. ....
Sử dụng hàm Os.ListDir [] và SHOTIL Mov [] để di chuyển tất cả các tệp. Giả sử bạn muốn di chuyển tất cả/nhiều tệp từ thư mục này sang thư mục khác, sau đó sử dụng HĐH ..

Di chuyển [] trong Python là gì?

Di chuyển [] hàm, cho phép chúng tôi di chuyển một tệp bằng Python.Trước khi chúng tôi khám phá hàm di chuyển [], trước tiên chúng tôi phải nhập thư viện Shutil vào mã của chúng tôi.Chúng ta có thể làm như vậy bằng cách sử dụng tuyên bố nhập Python này: Nhập Shutil.allows us to move a file using Python. Before we explore the move[] function, we must first import the shutil library into our code. We can do so using this Python import statement : import shutil.

Làm thế nào để bạn di chuyển tất cả các tệp trong một thư mục trong Python?

Dưới đây là các cách tiếp cận khác nhau bằng cách sử dụng người ta có thể lặp lại các tệp trong một thư mục bằng Python:..
Phương pháp 1: OS.ListDir [].
Phương pháp 2: OS.Scandir [].
Phương pháp 3: Mô -đun Pathlib ..
Phương pháp 4: OS.Walk [].
Phương pháp 5: Mô -đun toàn cầu ..

Làm thế nào để bạn gửi các tệp trong Python?

Cách tiếp cận từng bước:..
Cài đặt các phụ thuộc bằng cách sử dụng Cài đặt PIP tại dòng lệnh ..
Nhập các mô -đun cần thiết: HTTP.Máy chủ và Socketserver: Để lưu trữ trong trình duyệt.....
Gán cổng và tên của người dùng ..
Tìm địa chỉ IP của PC và chuyển đổi nó thành mã QR ..
Tạo yêu cầu HTTP ..
Hiển thị mã QR trong trình duyệt ..

Bài Viết Liên Quan

Chủ Đề