我要完成的工作是,在找到匹配项时在文件中搜索某个字符串,将文件上方的所有内容删除,然后保存文件。我是Python的新手,所以我可能做错了几件事。现在,它创建了一个新文件,但没有任何内容写入其中。
以下是我的代码:
file_type = ".php"
search_str = "}exit();}} ?><?php"
print("SANITIZING........")
print("FOLDERPATH being searched in: ", search_path)
print("FILETYPE being searched for : ", file_type)
print("STRING being searched : ", search_str)
# LOOPING THROUGH ALL FOLDERS AND FILES
for subdir, dirs, files in os.walk(search_path):
for file in files:
# Apply file type filter
if file.endswith(file_type):
bad_codes = ['exit();}} ?><?php']
orig_file = open(os.path.join(subdir, file))
for line in orig_file:
index = line.find(search_str)
if ( index != -1) :
new_file = open(os.path.join(subdir, '-clean2-copy-' + file), 'w')
if not any(bad_code in line for bad_code in bad_codes):
new_file.write(line)
fw.write("CREATED SANITIZED COPY OF BAD PHP FILE: " + os.path.join(subdir, file) + " " + str(index) + "\r\n")
答案 0 :(得分:0)
您可以使用布尔值标记非常简单地进行操作-我们将其称为found_str
。
found_str = False
for line in orig_file:
if search_str in line:
found_str = True
continue
if found_str:
new_file.write(line)
如果愿意,可以进行两个循环:一个循环查找字符串,一个循环写入文件的其余部分:
for line in orig_file:
if search_str in line:
break
for line in orig_file:
new_file.write(line)
这两种方法都能帮到您吗?