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!"