博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
删除可能不存在的文件的大多数pythonic方式
阅读量:2380 次
发布时间:2019-05-10

本文共 1812 字,大约阅读时间需要 6 分钟。

本文翻译自:

I want to delete the file filename if it exists. 我想删除文件filename如果存在)。 Is it proper to say 这是否合适

if os.path.exists(filename):    os.remove(filename)

Is there a better way? 有没有更好的办法? A one-line way? 单行方式?


#1楼

参考:


#2楼

returns True for folders as well as files. 为文件夹和文件返回True Consider using to check for whether the file exists instead. 考虑使用来检查文件是否存在。


#3楼

A more pythonic way would be: 一种更加pythonic的方式是:

try:    os.remove(filename)except OSError:    pass

Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists() and follows the python convention of overusing exceptions. 虽然这需要更多的行并且看起来非常难看,但它避免了对os.path.exists()的不必要的调用,并遵循过度使用异常的python约定。

It may be worthwhile to write a function to do this for you: 编写一个函数来为您执行此操作可能是值得的:

import os, errnodef silentremove(filename):    try:        os.remove(filename)    except OSError as e: # this would be "except OSError, e:" before Python 2.6        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory            raise # re-raise exception if a different error occurred

#4楼

Something like this? 像这样的东西? Takes advantage of short-circuit evaluation. 利用短路评估。 If the file does not exist, the whole conditional cannot be true, so python will not bother evaluation the second part. 如果文件不存在,则整个条件不能为真,因此python不会打扰第二部分的评估。

os.path.exists("gogogo.php") and os.remove("gogogo.php")

#5楼

根据Andy Jones的回答,真正的三元操作如何:

os.remove(fn) if os.path.exists(fn) else None

#6楼

Another way to know if the file (or files) exists, and to remove it, is using the module glob. 另一种知道文件(或文件)是否存在以及将其删除的方法是使用模块glob。

from glob import globimport osfor filename in glob("*.csv"):    os.remove(filename)

Glob finds all the files that could select the pattern with a *nix wildcard, and loops the list. Glob找到所有可以使用* nix通配符选择模式的文件,并循环列表。

转载地址:http://dbexb.baihongyu.com/

你可能感兴趣的文章
[ZZ]变速齿轮作者的文章--绝杀反外挂方案
查看>>
了解内核的装入地址和入口地址,vmlinux.bin与vmlinux
查看>>
内核里面对大小写字符的转换
查看>>
网络分层的好处是什么?
查看>>
thinking in linux 机制与策率
查看>>
linux samba服务与VISTA互通
查看>>
在svn和git之间选择
查看>>
龙星课程: 局部性原理在计算机和分布式系统中的应用
查看>>
eclipse的奇怪的更新方式
查看>>
MIPS技术公司官方对linux的支持信息
查看>>
openflow简介
查看>>
windows7配置虚拟AP的脚本
查看>>
windows7定时关机脚本
查看>>
ARM流水线结构的发展(ARM7~ARM11)
查看>>
Dalvik: 从makefile入门
查看>>
常用浮点数常量
查看>>
三角函数的特殊值的结果
查看>>
奇怪的X86
查看>>
有意思的C语言
查看>>
Basic Block
查看>>