I want to search a specific folder with files for words and then save the files with those words to another folder. I only get a blank new txt with my code. What might be wrong?
This is what I have:
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()
You should try the following modified code:
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()
NOTE: Copy files:
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)
Output:
>>> 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
Check folders:
>>>ll test_dir1
./
../
aaa.txt
asdf.log
>>>ll test_dir2
./
../
aaa.txt
asdf.log
The code has indentation problem. Also, you perform for word in line.lower().split():
lower and check here however,
if word in {"user", "password", "username", "pass","secret", "key", "backdoor", "ip"}:
you don't perform lower and then check here.
Might be you have to do
if word.lower() in {"user", "password", "username", "pass","secret", "key", "backdoor", "ip"}:
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.