作者Holocaust123 (奔跑的蜗牛)
看板Python
标题[问题] 如何取得os.listdir()结果的绝对路径
时间Wed Nov 10 00:20:11 2010
#coding=utf8
import os, shutil
# 如下所见, cache_folders 这个 list 的 element 皆为资料夹路径.
# 这些路径的档案分隔符号颇乱, 有些用/, 有些用\, 有些用//, 有些用\\,
# 且多半有混用的情况
cache_folders = \
[
'C:\\Documents and Settings\\user\\Local Settings\\Application Data\\Mozilla\\Firefox\\Profiles\\uxkeooir.lite\\Cache',
'C:\\Documents and Settings\\user/Local Settings/Application Data/K-Meleon\\aqu123v4.default\\Cache',
u'C:\\Documents and Settings\\user/Local Settings/Temporary Internet Files/',
ur'D:/测试档 output 备份/',
#...过多, 故省略
]
# 现在, 我想把cache_folders中的每个资料夹中的档案通通删掉:
for
folder in
cache_folders:
for
f in os.listdir(
folder):
if(os.path.isfile(
f)): # 档案可能是file
os.remove(
f)
else: # 也可能是directory
shutil.rmtree(
f)
---
但
f毕竟不是档案路径 要先取得路径才能删除
我想过几个方法:
1) 把
f 的路径 append 在
folder的路径後面
for
folder in
cache_folders:
for
f in os.listdir(
folder):
folder = refine(folder) #refine是另外写的函式, 目的是把folder改成以"/"结尾
f = folder + f
if(os.path.isfile(
f)): # 档案可能是file
os.remove(
f)
else: # 也可能是directory
shutil.rmtree(
f)
2) 移到folder路径後再删除底下的档案
for
folder in
cache_folders:
for
f in os.listdir(
folder):
os.chdir(folder)
if(os.path.isfile(
f)): # 档案可能是file
os.remove(
f)
else: # 也可能是directory
shutil.rmtree(
f)
我想请教的是:
a. 有没有办法透过Python内建函式直接取得某资料夹内所有档案的绝对路径?
我的意思大概是这样:
for
folder in
cache_folders
for
f in
list_abspath(
folder): #有
list_abspath这种函式吗?
if(os.path.isfile(
f)): # 档案可能是file
os.remove(
f)
else: # 也可能是directory
shutil.rmtree(
f)
b. 除了上述几种方法, 还有什麽推荐的删档案方法吗?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.30.32
※ 编辑: Holocaust123 来自: 140.112.30.32 (11/10 01:00)
1F:→ huggie:我都改用用glob了 11/10 14:12