Hướng dẫn remove multiple files python - loại bỏ nhiều tệp python

Đã hỏi 3 năm, 8 tháng trước 3 years, 8 months ago

Đã xem 567 lần 567 times

Tôi đang chơi xung quanh với một số kịch bản Python và tôi gặp phải một vấn đề với kịch bản tôi đang viết. Nó được cho là tìm tất cả các tệp trong một thư mục đáp ứng các tiêu chí và sau đó xóa nó. Tuy nhiên, nó tìm thấy các tệp, nhưng tại thời điểm xóa tệp, nó nói rằng tệp không được tìm thấy.

Đây là mã của tôi:

import os
for filename in os.listdir('C:\\New folder\\'):
    if filename.endswith(".rdp"):
        os.unlink(filename)

Và đây là lỗi tôi nhận được sau khi chạy nó:

FilenotFounderRor: [WinError 2] Hệ thống không thể tìm thấy tệp được chỉ định:

Ai đó có thể hỗ trợ điều này không?

Khi được hỏi ngày 27 tháng 2 năm 2019 lúc 23:00Feb 27, 2019 at 23:00

2

os.unlink đưa đường dẫn đến tệp, không chỉ

import os

dirname = 'C:\\New folder\\'

for filename in os.listdir(dirname):
    if filename.endswith(".rdp"):

        # Add your "dirname" to the file path
        os.unlink(dirname + filename)
0 của nó. Hãy thử trước khi chờ đợi
import os

dirname = 'C:\\New folder\\'

for filename in os.listdir(dirname):
    if filename.endswith(".rdp"):

        # Add your "dirname" to the file path
        os.unlink(dirname + filename)
0 của bạn với
import os

dirname = 'C:\\New folder\\'

for filename in os.listdir(dirname):
    if filename.endswith(".rdp"):

        # Add your "dirname" to the file path
        os.unlink(dirname + filename)
2. Như thế nàypath to the file, not only its
import os

dirname = 'C:\\New folder\\'

for filename in os.listdir(dirname):
    if filename.endswith(".rdp"):

        # Add your "dirname" to the file path
        os.unlink(dirname + filename)
0. Try pre-pending your
import os

dirname = 'C:\\New folder\\'

for filename in os.listdir(dirname):
    if filename.endswith(".rdp"):

        # Add your "dirname" to the file path
        os.unlink(dirname + filename)
0 with the
import os

dirname = 'C:\\New folder\\'

for filename in os.listdir(dirname):
    if filename.endswith(".rdp"):

        # Add your "dirname" to the file path
        os.unlink(dirname + filename)
2. Like this

import os

dirname = 'C:\\New folder\\'

for filename in os.listdir(dirname):
    if filename.endswith(".rdp"):

        # Add your "dirname" to the file path
        os.unlink(dirname + filename)

Hướng dẫn remove multiple files python - loại bỏ nhiều tệp python

Khelwood

53.4K13 Huy hiệu vàng80 Huy hiệu bạc101 Huy hiệu đồng13 gold badges80 silver badges101 bronze badges

Đã trả lời ngày 27 tháng 2 năm 2019 lúc 23:05Feb 27, 2019 at 23:05

Hướng dẫn remove multiple files python - loại bỏ nhiều tệp python

Molamkmolamkmolamk

3.9761 Huy hiệu vàng12 Huy hiệu bạc22 Huy hiệu đồng1 gold badge12 silver badges22 bronze badges

Bạn có thể sử dụng OS.walk, tuy nhiên nó có thể đi sâu hơn bạn muốn:

import os

for root, sub, file in os.walk("/media/"):
    if file.endswith(".rdp"):
        os.unlink(f'{root}/{file}')

Đã trả lời ngày 27 tháng 2 năm 2019 lúc 23:20Feb 27, 2019 at 23:20

AriariAri

4.4135 Huy hiệu vàng36 Huy hiệu bạc97 Huy hiệu Đồng5 gold badges36 silver badges97 bronze badges


Bạn có thể xóa một tệp hoặc một thư mục trống duy nhất với các chức năng trong mô -đun HĐH.

Thí dụ

Ví dụ: nếu bạn muốn xóa tệp my_file.txt,

>>> import os
>>> os.remove('my_file.txt')

Đối số cho Os.Remove phải là đường dẫn tuyệt đối hoặc tương đối.

Để xóa nhiều tệp, chỉ cần lặp qua danh sách các tệp của bạn và sử dụng chức năng trên. Nếu bạn muốn xóa một thư mục chứa tất cả các tệp bạn muốn xóa, bạn có thể xóa thư mục như sau:

>>> import shutil
>>> shutil.rmtree('my_folder')

Thí dụ

Ví dụ: nếu bạn muốn xóa tệp my_file.txt,

import os, re, os.path
pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.match(pattern, x), files):
        os.remove(os.path.join(root, file))

Hướng dẫn remove multiple files python - loại bỏ nhiều tệp python

Đối số cho Os.Remove phải là đường dẫn tuyệt đối hoặc tương đối.

  • Để xóa nhiều tệp, chỉ cần lặp qua danh sách các tệp của bạn và sử dụng chức năng trên. Nếu bạn muốn xóa một thư mục chứa tất cả các tệp bạn muốn xóa, bạn có thể xóa thư mục như sau:
  • Bạn cũng có thể sử dụng Regex để xóa các tệp khớp với một mẫu. Ví dụ,
  • Cập nhật vào ngày 12 tháng 12 năm 2019 07:05:10
  • Câu hỏi và câu trả lời liên quan
  • Làm thế nào để xóa tất cả các tệp trong một thư mục với Python?
  • Làm thế nào để đổi tên nhiều tệp trong một thư mục trong Python?
  • Chương trình Java để xóa tất cả các tệp trong thư mục một cách đệ quy (chỉ các tệp)
  • Làm thế nào để xóa một thư mục Python một cách hiệu quả?
  • Làm thế nào để sao chép các tệp vào một thư mục mới bằng Python?
  • Xóa một thư mục trong Java
  • Làm thế nào để sao chép các tệp vào một thư mục trong C#?
  • Làm thế nào để tìm tất cả các tệp trong một thư mục với phần mở rộng .txt trong Python?
  • Làm cách nào để liệt kê tất cả các tệp của một thư mục trong Python?
  • Làm thế nào tôi có thể lặp lại các tệp trong một thư mục nhất định trong Python?
  • Làm thế nào để liệt kê tất cả các tệp trong một thư mục bằng Java?
  • Làm thế nào để giải nén tất cả các tệp bị nén trong thư mục Linux?

Bỏ qua nội dung chính

Trình duyệt này không còn được hỗ trợ.

Nâng cấp lên Microsoft Edge để tận dụng các tính năng mới nhất, cập nhật bảo mật và hỗ trợ kỹ thuật.

Cách sao chép, xóa và di chuyển các tệp và thư mục (Hướng dẫn lập trình C#)

  • Bài báo
  • 15/09/2021
  • 3 phút để đọc

Trong bài viết này

Các ví dụ sau đây cho thấy cách sao chép, di chuyển và xóa các tệp và thư mục một cách đồng bộ bằng cách sử dụng System.io.file, System.io.Directory, System.io.FileInfo và System.io.DirectoryInfo các lớp từ hệ thống .Io không gian tên. Những ví dụ này không cung cấp một thanh tiến trình hoặc bất kỳ giao diện người dùng nào khác. Nếu bạn muốn cung cấp hộp thoại tiến độ tiêu chuẩn, hãy xem cách cung cấp hộp thoại tiến trình cho các hoạt động tệp.

Sử dụng System.io.FilesystemWatcher để cung cấp các sự kiện cho phép bạn tính toán tiến trình khi hoạt động trên nhiều tệp. Một cách tiếp cận khác là sử dụng nền tảng gọi để gọi các phương thức liên quan đến tệp có liên quan trong shell windows. Để biết thông tin về cách thực hiện các hoạt động tệp này một cách không đồng bộ, hãy xem I/O tệp không đồng bộ.

Ví dụ

Ví dụ sau đây cho thấy cách sao chép tệp và thư mục.

// Simple synchronous file copy operations with no user interface.
// To run this sample, first create the following directories and files:
// C:\Users\Public\TestFolder
// C:\Users\Public\TestFolder\test.txt
// C:\Users\Public\TestFolder\SubDir\test.txt
public class SimpleFileCopy
{
    static void Main()
    {
        string fileName = "test.txt";
        string sourcePath = @"C:\Users\Public\TestFolder";
        string targetPath =  @"C:\Users\Public\TestFolder\SubDir";

        // Use Path class to manipulate file and directory paths.
        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);

        // To copy a folder's contents to a new location:
        // Create a new target folder.
        // If the directory already exists, this method does not create a new directory.
        System.IO.Directory.CreateDirectory(targetPath);

        // To copy a file to another location and
        // overwrite the destination file if it already exists.
        System.IO.File.Copy(sourceFile, destFile, true);

        // To copy all the files in one directory to another directory.
        // Get the files in the source folder. (To recursively iterate through
        // all subfolders under the current directory, see
        // "How to: Iterate Through a Directory Tree.")
        // Note: Check for target path was performed previously
        //       in this code example.
        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);

            // Copy the files and overwrite destination files if they already exist.
            foreach (string s in files)
            {
                // Use static Path methods to extract only the file name from the path.
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);
            }
        }
        else
        {
            Console.WriteLine("Source path does not exist!");
        }

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

Ví dụ sau đây cho thấy cách di chuyển các tập tin và thư mục.

// Simple synchronous file move operations with no user interface.
public class SimpleFileMove
{
    static void Main()
    {
        string sourceFile = @"C:\Users\Public\public\test.txt";
        string destinationFile = @"C:\Users\Public\private\test.txt";

        // To move a file or folder to a new location:
        System.IO.File.Move(sourceFile, destinationFile);

        // To move an entire directory. To programmatically modify or combine
        // path strings, use the System.IO.Path class.
        System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
    }
}

Ví dụ sau đây cho thấy cách xóa các tập tin và thư mục.

// Simple synchronous file deletion operations with no user interface.
// To run this sample, create the following files on your drive:
// C:\Users\Public\DeleteTest\test1.txt
// C:\Users\Public\DeleteTest\test2.txt
// C:\Users\Public\DeleteTest\SubDir\test2.txt

public class SimpleFileDelete
{
    static void Main()
    {
        // Delete a file by using File class static method...
        if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
        {
            // Use a try block to catch IOExceptions, to
            // handle the case of the file already being
            // opened by another process.
            try
            {
                System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
                return;
            }
        }

        // ...or by using FileInfo instance method.
        System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt");
        try
        {
            fi.Delete();
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        // Delete a directory. Must be writable or empty.
        try
        {
            System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest");
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
        // Delete a directory and all subdirectories with Directory static method...
        if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest"))
        {
            try
            {
                System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true);
            }

            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        // ...or with DirectoryInfo instance method.
        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\Users\Public\public");
        // Delete this dir and all subdirs.
        try
        {
            di.Delete(true);
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Xem thêm

  • System.IO
  • Hướng dẫn lập trình C#
  • Hệ thống tệp và sổ đăng ký (Hướng dẫn lập trình C#)
  • Cách cung cấp hộp thoại tiến trình cho các hoạt động tệp
  • Tệp và luồng I/O
  • Nhiệm vụ I/O chung

Nhận xét

Gửi và xem phản hồi cho