如何在Python中通过扩展名删除文件?

时间:2015-09-29 02:29:19

标签: python

我正在努力制作一个脚本来删除" .zip"扩展

public class Loop implements Runnable {
    private final Object member = new Object();
    public final void run() {
        // This code runs, but it shouldn't
        synchronized (member) { // Throws NPE
            ...
        }
        // Hook for subclasses
        try {
            subclassRun();
        } finally {
            // Mandatory cleanup (unrelated to question)
        }
}

public class DoThingInALoop extends Loop {
    public void subclassRun() { ... }
    public void stopDoingThingsInALoop() {
        // Set instance member that on next loop iteration signals thread to return
    }
}

public class Boss {
    private final DoThingsInALoop toBeMocked;
    public Boss(final DoThingsInALoop toBeMocked) {
        this.toBeMocked = toBeMocked;
    }
    public void start() {
        // Simplified
        new Thread(toBeMocked).start();
    }
    public void stop() {
        toBeMocked.stopDoingThingsInALoop();
    }
}


public class TestClass {
    @Test
    public void aTest() {
        // Setup Mocks
        DoThingsInALoop mockLoop = mock(DoThingsInALoop.class);
        Boss boss = new Boss(mockLoop);

        // Run test
        boss.start();

        // After the above line runs, a new thread is started and
        // the run() method of `Loop` executes until the NPE
        // is hit when it attempts to access a member variable
        // which is of course not set because it is a mocked object

        ...
    }
}

每当我运行脚本时,我都会得到:

import sys
import os
from os import listdir

test=os.listdir("/Users/ben/downloads/")

for item in test:
    if item.endswith(".zip"):
        os.remove(item)

cities1000.zip显然是我的下载文件夹中的一个文件。

我在这里做错了什么? os.remove是否需要文件的完整路径?如果这是问题,那么如何在没有完全重写的情况下在当前脚本中执行此操作。

7 个答案:

答案 0 :(得分:21)

您可以将路径设置为os.path.join变量,然后使用os.remove作为import os dir_name = "/Users/ben/downloads/" test = os.listdir(dir_name) for item in test: if item.endswith(".zip"): os.remove(os.path.join(dir_name, item))

For Each listItem As ListViewItem In lvOrder.Items
    If Not lvOrder.Items.ContainsKey("Burger") Then

        listItem.Text = "Burger"
        listItem.SubItems.Add(1) 'Quantity
        listItem.SubItems.Add(50.0) 'Price

        lvOrder.Items.Add(listItem)
     Else
        MessageBox.Show("Item already exist")
    End If
Next

答案 1 :(得分:4)

对于此操作,您需要将文件名附加到文件路径,以便命令知道您正在查找的文件夹。

您可以使用os.path.join命令在python中以可移植的方式正确执行此操作 例如:

import sys
import os

directory = "/Users/ben/downloads/"
test = os.listdir( directory )

for item in test:
    if item.endswith(".zip"):
        os.remove( os.path.join( directory, item ) )

答案 2 :(得分:2)

避免一次又一次地加入自己的替代方法:使用glob模块加入一次,然后让它直接返回路径。

import glob
import os

dir = "/Users/ben/downloads/"

for zippath in glob.iglob(os.path.join(dir, '*.zip')):
    os.remove(zippath)

答案 3 :(得分:2)

在这个问题上只留下我的两分钱:如果你想别致,你可以使用 glob package 中的 globiglob,如下所示:

import glob
import os

files_in_dir = glob.glob('/Users/ben/downloads/*.zip')
# or if you want to be fancy, you can use iglob, which returns an iterator:
files_in_dir = glob.iglob('/Users/ben/downloads/*.zip')

for _file in files_in_dir:
    print(_file) # just to be sure, you know how it is...
    os.remove(_file)

答案 4 :(得分:1)

我认为您可以使用 Pathlib-- 一种现代方式,如下所示:

import pathlib


dir = pathlib.Path("/Users/ben/downloads/")
zip_files = dir.glob(dir / "*.zip")
for zf in zip_files:
    zf.unlink()

如果你想递归删除所有 zip 文件,就这样写:

import pathlib


dir = pathlib.Path("/Users/ben/downloads/")
zip_files = dir.rglob(dir / "*.zip")  # recursively
for zf in zip_files:
    zf.unlink()

答案 5 :(得分:0)

将目录添加到文件名

os.remove("/Users/ben/downloads/" + item)

编辑:或使用os.chdir更改当前工作目录。

答案 6 :(得分:0)

origfolder = "/Users/ben/downloads/"
test = os.listdir(origfolder)

for item in test:
    if item.endswith(".zip"):
        os.remove(os.path.join(origfolder, item))

dirname不包含在os.listdir输出中。您必须附加它以引用该函数返回的列表中的文件。