我要搜索包含文件的单词的特定文件夹,然后将包含这些单词的文件保存到另一个文件夹。我的代码只得到一个空白的新txt。怎么了?
这就是我所拥有的:
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()
答案 0 :(得分:1)
您应该尝试以下修改的代码:
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
答案 1 :(得分:0)
代码有缩进问题。另外,您执行
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"}:
。