我正在构建一个简单的功能(删除文件)。但最后我想返回有效删除的文件列表。
这是函数:
def deleteFiles(files):
# empty list
RemovedFiles = list()
for file in files:
# Delete the file
if os.remove(file):
RemovedFiles.append(file)
return RemovedFiles
我运行这个函数:
print deleteFiles([/home/xyz/xyz.zip])
这有效地删除了 xyz.zip 但返回一个空列表:[]
。我在这里做错了什么?
最佳答案
问题是 os.remove
没有返回任何东西。
但是你可以try
和except
:
for filename in filenames:
try:
# try to remove the file
os.remove(filename)
except OSError:
pass
# file not removed (maybe does not exist or is write-protected)
# you may report an error here
else:
# this executes only if os.remove was successful
RemovedFiles.append(filename)
关于python - 如何显示列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7915666/