Python находит слова в папке и сохраняет новые файлы - PullRequest
0 голосов
/ 15 мая 2019

Я хочу выполнить поиск слов в определенной папке с файлами, а затем сохранить файлы с этими словами в другой папке. Я получаю только новый текст с моим кодом. Что может быть не так?

Вот что у меня есть:

from os import system, listdir, path
system("cls")
system("color b9")
FILE = open("CodeR.txt", "a")
desktop_dir = r"C:\Users\ilan\Desktop"
for fn in listdir(desktop_dir):
fn_w_path = path.join(desktop_dir, fn)
if path.isfile(fn_w_path):
    with open(fn_w_path) as filee:
        for line in filee:
            for word in line.lower().split():
                if word in {"user", "password", "username",             "pass",
                            "secret", "key", "backdoor", "ip"}:
                    FILE.write(word + "\n")
FILE.close()

Ответы [ 2 ]

1 голос
/ 15 мая 2019

Вы должны попробовать следующий модифицированный код:

from os import system, listdir, path
system("cls")
system("color b9")
FILE = open("CodeR.txt", "w")  # Should use "w" as write file 
desktop_dir = path.join("C:", "Users", "ilan", "Desktop")  # Should use path.join to create paths
for fn in listdir(desktop_dir):
    fn_w_path = path.join(desktop_dir, fn)
    if path.isfile(fn_w_path):
        with open(fn_w_path, "r") as filee:  # Should use "r" as read file
            for line in filee.readlines():  # Should use readlines() method. It give a list with lines.
                for word in line.lower().split():
                    if word in ["user", "password", "username",             "pass",
                            "secret", "key", "backdoor", "ip"]:  # Convert it to list. 
                        FILE.write(word + "\n")
FILE.close()

Примечание: Копировать файлы:

import os
import shutil

for root, dirs, files in os.walk("test_dir1", topdown=False):
    for name in files:
        current_file = os.path.join(root, name)
        destination = current_file.replace("test_dir1", "test_dir2")
        print("Found file: %s" % current_file)
        print("File copy to: %s" % destination)
        shutil.copy(current_file, destination)

Выход:

>>> python test.py 
Found file: test_dir1/asdf.log
File copy to: test_dir2/asdf.log
Found file: test_dir1/aaa.txt
File copy to: test_dir2/aaa.txt

Проверить папки:

>>>ll test_dir1 
./
../
aaa.txt
asdf.log

>>>ll test_dir2
./
../
aaa.txt
asdf.log
0 голосов
/ 15 мая 2019

Код имеет проблему с отступом. Также вы выполняете for word in line.lower().split():

ниже и отметьте здесь, однако,

if word in {"user", "password", "username", "pass","secret", "key", "backdoor", "ip"}:

Вы не выполните ниже, а затем проверьте здесь.

Может быть, вы должны сделать

if word.lower() in {"user", "password", "username", "pass","secret", "key", "backdoor", "ip"}:.

...