2017-01-06 6 views
1

Ich schreibe ein Python-Skript, um alle .py-Dateien mit entsprechenden .pyc-Dateien zu finden und zu entfernen. Wie extrahiere ich diese Dateiliste und entferne sie?Suchen und Löschen von Dateien mit Python-Skript

Zum Beispiel: Sehen Sie scheint, dass eine Datei in/foo/bar:

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

Ich möchte file.py, file2.py löschen und nicht file3.py wie es .pyc Datei nicht entspricht. und ich möchte in allen Ordnern unter '/' tun.

Gibt es einen einzigen Bash-Code für dasselbe?

PS: Ich bin mit CentOS 6.8, python2.7 mit

+0

Interessante Anfrage. Sind Sie sicher, dass Sie '.pyc' Dateien, die entsprechende' .py' Dateien haben, nicht löschen wollen? :) –

+0

Nein, es ist eine Kundenanfrage –

Antwort

1

Hier ist meine Lösung.

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) 

PS: Newbie in Python-Skripting.

0

ist dies eine sehr betriebssystemnahe Lösung

vielleicht einen Shell-Skript aus den folgenden Befehlen machen und sie von Python aufrufen subprocess.call mit (How to call a shell script from python code?, Calling an external command in Python)

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

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

aus den Einträgen dieser Dateien entfernen Pfad und endend Datei sed oder basename mit:

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

for f in $(cat /tmp/py.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)

awk 'FNR==NR{a[$1];next}($1 in a){print}' /tmp/pyc.txt /tmp/py.txt > /tmp/rm.txt (https://unix.stackexchange.com/questions/125155/compare-two-files-for-matching-lines-and-store-positive-results)

for f in $(cat /tmp/rm.txt) ; do rm $f done (Unix: How to delete files listed in a file)

+0

Wenn möglich, brauche ich Ein-Liner-Code für die gleiche? –

0

Der folgende Code funktioniert für ein einzelnes Layer-Verzeichnis. (Hinweis: Ich war mir nicht sicher, wie Sie mehrere Ebenen von Ordnern verwalten wollten. ZB wenn Sie A.py in einem Ordner und A.pyc in einem anderen Ordner haben, zählen beide als vorhanden oder müssen sie identisch sein ? Schicht aus dem gleichen Ordner Wenn letzteres der Fall, sollte es recht einfach nur Schleife durch die Ordner und nur innerhalb jeder Schleife diesen Code aufrufen)

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 
+0

Code funktioniert gut. Aber manchmal in dirlist.pyc Datei kommt zuerst dann .py, Zum Beispiel: 'Liste [1] = argu.py Liste [2] = test1.pyc Liste [3] = selbst.py . . . Liste [10] = test.py' wird es jedes Problem während des Vergleichs verursachen? –

+0

Versuchen Sie, eine Sortierung nach dirlist hinzuzufügen. Z.B. 'dirlist = sort (dirlist)' Das sollte sicherstellen, dass .pyc direkt hinter der entsprechenden .py-Datei steht. – Elliptica

+0

Um es klar zu sagen, die Python-Sortier-Syntax ist 'dirList.sort()'. Ich habe es meinem obigen Code hinzugefügt. – Elliptica

1

Bash Lösung:

#!/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 
Verwandte Themen