linux - 使用python脚本查找和删除文件

标签 linux bash python-2.7

<分区>

我正在编写一个 Python 脚本来查找并删除所有具有相应 .pyc 文件的 .py 文件。 如何提取此文件列表并将其删除?

例如:考虑在/foo/bar 中有一些文件:

file.py
file.pyc
file3.py
file2.py
file2.pyc...etc

我想删除 file.py、file2.py 而不是 file3.py,因为它没有相应的 .pyc 文件。 我想在“/”下的所有文件夹中执行此操作。

是否有相同的一行 bash 代码?

P.S : 我使用的是 CentOS 6.8,有 python2.7

最佳答案

这是我的解决方案:

    import os
    ab=[]
    for roots,dirs,files in os.walk("/home/foo/bar/"):
        for file in files:
            if file.endswith(".py"):
                ab.append(os.path.join(roots,file))
    bc=[]
    for i in range(len(ab)):
        bc.append(ab[i]+"c")
    xy=[]
    for roots,dirs,files in os.walk("/home/foo/bar/"):
        for file in files:
            if file.endswith(".pyc"):
                xy.append(os.path.join(roots,file))
    ex=[x[:-1] for x in bc if x in xy]
    for i in ex:
        os.remove(i)

P.S:python 脚本新手。

关于linux - 使用python脚本查找和删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41499031/

相关文章:

bash - bash中 `!#`有什么用?

bash - xdotool 记录器

python - 在 Python 中 n 次失败后退出无限循环的最佳方法是什么?

python - 删除 None 值的管道

arrays - JQ 对嵌套对象中的字段进行过滤

python-2.7 - 导入 matplotlib._png 作为 _png 导入 : Error: DLL load failed: The specified module could not be found

linux - Linux 服务器上的闪存

linux - 从 makefile 并行运行两个进程

linux - sudo dpkg -i mod-pagespeed-*.deb 给出 "not a debian format archive"错误

linux - 在 Linux 上的 stderr 上打印错误消息