如何在Python中按扩展名删除文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32834731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete a file by extension in Python?
提问by stephan
I was messing around just trying to make a script that deletes items by ".zip" extension.
我只是试图制作一个通过“.zip”扩展名删除项目的脚本。
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)
Whenever I run the script I get:
每当我运行脚本时,我都会得到:
OSError: [Errno 2] No such file or directory: 'cities1000.zip'
cities1000.zip is obviously a file in my downloads folder.
city1000.zip 显然是我下载文件夹中的一个文件。
What did I do wrong here? Is the issue that os.remove requires the full path to the file? If this is the issue, than how can I do that in this current script without completely rewriting it.
我在这里做错了什么?问题是 os.remove 需要文件的完整路径吗?如果这是问题所在,那么我如何在不完全重写的情况下在当前脚本中做到这一点。
采纳答案by idjaw
You can set the path in to a dir_name
variable, then use os.path.join
for your os.remove
.
您可以将路径设置为dir_name
变量,然后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))
回答by David
Prepend the directory to the filename
将目录添加到文件名之前
os.remove("/Users/ben/downloads/" + item)
EDIT: or change the current working directory using os.chdir
.
编辑:或使用os.chdir
.
回答by Serdalis
For this operation you need to append the file name on to the file path so the command knows what folder you are looking into.
对于此操作,您需要将文件名附加到文件路径上,以便命令知道您正在查看哪个文件夹。
You can do this correctly and in a portable way in python using the os.path.join
command.
For example:
您可以使用该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 ) )
回答by johncruise
origfolder = "/Users/ben/downloads/"
test = os.listdir(origfolder)
for item in test:
if item.endswith(".zip"):
os.remove(os.path.join(origfolder, item))
The dirname is not included in the os.listdir output. You have to attach it to reference the file from the list returned by said function.
目录名不包含在 os.listdir 输出中。您必须附加它以从所述函数返回的列表中引用文件。
回答by ShadowRanger
Alternate approach that avoids join-ing yourself over and over: Use glob
module to join once, then let it give you back the paths directly.
避免反复加入自己的替代方法:使用glob
模块加入一次,然后让它直接返回路径。
import glob
import os
dir = "/Users/ben/downloads/"
for zippath in glob.iglob(os.path.join(dir, '*.zip')):
os.remove(zippath)