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

时间:2017-01-06 04:38:44

标签: 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

4 个答案:

答案 0 :(得分:1)

这是我的解决方案:

    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 scriptiing中的新手。

答案 1 :(得分:1)

Bash解决方案:

#!/bin/bash

find  /foo/bar -name "*.py" -exec ls  {} \;  > file1.txt
find  /foo/bar/ -name "*.pyc" -exec ls {} \; > file2.txt
p=`wc -l file1.txt| cut -d' ' -f1`
for ((c=1;c<=$p;c++))
do
  grep `sed -n ${c}p file1.txt | sed s/$/c/g` file2.txt > /dev/null
  if [ $? -eq 0 ]
     then
       list=`sed -n ${c}p file1.txt`
           echo " exist : $list"
           rm -rf `sed -n ${c}p file1.txt`
  fi
 done

答案 2 :(得分:0)

这是一个非常靠近操作系统的解决方案

可以使用以下命令创建一个shell脚本,并使用${param.myvar} ${param[name]} // here `name` is another EL variable with value `name = "myvar"` ${param["myvar"]} ${param['myvar']} How to call a shell script from python code?Calling an external command in Python

从python中调用它

subprocess.call

find . -name "*.pyc" > /tmp/pyc.txt

从这些文件的条目中删除使用find . -name "*.py" > /tmp/py.txtsed结尾的路径和文件:

basename

for f in $(cat /tmp/pyc.txt) ; do sed 's/.*\///' remove path sed 's/\.[^.]*$//' remove file ending done

https://unix.stackexchange.com/questions/44735/how-to-get-only-filename-using-sed

for f in $(cat /tmp/py.txt) ; do sed 's/.*\///' remove path sed 's/\.[^.]*$//' remove file ending donehttps://unix.stackexchange.com/questions/125155/compare-two-files-for-matching-lines-and-store-positive-results

awk 'FNR==NR{a[$1];next}($1 in a){print}' /tmp/pyc.txt /tmp/py.txt > /tmp/rm.txtUnix: How to delete files listed in a file

答案 3 :(得分:0)

以下代码适用于单层目录。 (注意:我不确定你想要如何处理多层文件夹 - 例如,如果你在一个文件夹中有A.py而在另一个文件夹中有A.pyc,那么它是否同时存在,或者它们必须位于同一文件夹的同一层中?如果是后一种情况,只需循环浏览文件夹并在每个循环中调用此代码就相当简单。)

import os

# Produces a sorted list of all files in a directory
dirList = os.listdir(folder_path)   # Use os.listdir() if want current directory
dirList.sort()

# Takes advantage of fact that both py and pyc files will share same name and
# that pyc files will appear immediately after their py counterparts in dirList

lastPyName = ""

for file in dirList:
    if file[-3:] == ".py":
        lastPyName = file[:-3]
    elif file[-4:] == ".pyc":
        if lastPyName == file[:-4]:
            os.remove(lastPyName + ".py")
            os.remove(lastPyName + ".pyc") # In case you want to delete this too