python - 如何显示列表?

标签 python file-io

我正在构建一个简单的功能(删除文件)。但最后我想返回有效删除的文件列表。

这是函数:

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 没有返回任何东西。

但是你可以tryexcept:

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/

相关文章:

c# - 在 C# 中使用 LockFileEX

c++ - ifstream.good() 和 bool(ifstream) 的区别

python - python 2.7 中需要密码的 SSL 连接

Python 和内存映射?

python - 禁用 Python 模块

python - 删除系列/数据帧多索引中的列

c++ - 为什么我的输入文件中的数字不进入我的数组 C++?

java - file.exists() 当文件存在时返回 false

c# - 从 WPF 中的包 URI 打开文件

iterator - 使用 python 连接上一句和下一句