pythonremove
Ⅰ python如何删除这个文件夹里的全部文件
如果是连着文件夹一起删就是shutil.rmtree( src)
如果是只删除内容和子文件夹可以用os.walk 遍历文件夹,拿到文件和文件夹再删除,也可以连着文件夹一起删了再建一个
Ⅱ python2 os.removedirs 和 rmdir的区别
直接在命令行python2
然后
import os
help(os.removedirs)
结果如下:
removedirs(name)
removedirs(path)
Super-rmdir; remove a leaf directory and all empty intermediate
ones. Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole path is
consumed or an error occurs. Errors ring this latter phase are
ignored -- they generally mean that a directory was not empty.
结论:
rmdir只能删除空文件夹
os.removedirs是递归删除文件夹(里面只能有空文件夹)
Ⅲ python 删除任意值
importrandom
test=['zhangsan','lisi','wangwu','zhaoliu','guoer','heihei','gaga']
#---------------------------
defremoveItem(source,count):
sample=random.sample(source,count)
foriteminsample:
source.remove(item)
print('Remove:',sample)
returnsource
#---------------------------
count=len(test)
ifcount%2==1:
test=removeItem(test,1)
whilelen(test)!=2:
test=removeItem(test,2)
print('Remain:',test)
输出结果:
Remove: ['gaga']
Remove: ['zhangsan', 'wangwu']
Remove: ['lisi', 'guoer']
Remain: ['zhaoliu', 'heihei']
Ⅳ python remove问题
因为当b指向列表中的第一个元素时,a.remove(4)删除了4,但是remove函数并没有执行完,而是将a列表中索引号大于删除元素索引号的所有元素依次向前移一位,
这时a列表变成了[8,24,5,6,8,4,5],而b继续执行,指向列表中的第二个元素24,所以删除了24,以此类推,所以a列表最后没有被完全删除,剩下[8, 5, 8, 5],
要全部删除a列表可以始终删除a[0],但要保证删除次数等于列表长度
完整的Python程序如下
a=[4,8,24,5,6,8,4,5]
forindexinrange(0,len(a)):
print(a[0])
a.remove(a[0])
print(a)
源代码(注意代码缩进)
Ⅳ python 怎么删除文件
1、创建python文件,testremove.py;
Ⅵ Python中如何删除一个文件
使用os模块中的remove()方法。
importos
help(os.remove)
Helponbuilt-infunctionremoveinmoleposix:
remove(...)
remove(path)
Removeafile(sameasunlink(path)).
(END)
Ⅶ python中从列表中用for循环删除(remove方法)停用词特别慢,有快一点的方法吗
python中最好不要在list遍历中使用list.remove方法:
remove 仅仅 删除一个值的首次出现。
如果在 list 中没有找到值版,程序会抛出一个异常
- 最后,权你遍历自己时候对自己的内容进行删除操作,效率显然不高,还容易出现各种难debug的问题
建议使用新的list存储要保留的内容,然后返回这个新list。比如
a_list=[1,2,3,4,5]
needs_to_be_removed=[3,4,5]
result=[]
forvina_list:
ifvnotinneeds_to_be_removed:
result.append(v)
printresult
Ⅷ Python中set集合中的remove和discard
历史原因不知道。
比如discard是remove的改进版呢?
discard没有报错可以不引起程序的报错。
remove会报错,可以用try catch抓报错,然后可以触发自定义事件,而discard就不能触发了,因为返回了默认值。(当然想达到办法都是有的)
Ⅸ Python如何删除文件及文件夹
删除文件:os.remove(filepath)
删除文件夹 shutil.rmtree(filepath,True)
示例:删除目录/tmp/test下文件以及文件夹
#!/usr/bin/env pythonimport osimport shutilfilelist=[]rootdir="/tmp/test"filelist=os.listdir(rootdir)for f in filelist: filepath = os.path.join( rootdir, f ) if os.path.isfile(filepath): os.remove(filepath) # 删除文件
print filepath+" removed!" elif os.path.isdir(filepath): shutil.rmtree(filepath,True) # 删除文件夹
print "dir "+filepath+" removed!"