I've been working on this for the past week and suddenly it doesn't want to take my input for my directory. Here's my code with comments explaining everything...
# Allows us to manipulate directorys
import os
# Allows us to utilize regular expression
import re
# Allows us to open and manipulate zipfiles
import zipfile
# The directory we/re searching in, file search with regex, and line within file with regex
directory = input("Enter directory to search: ")
fileregex = input("Enter filename regex: ")
lineregex = input("Enter line regex: ")
# Walk through the directory and all subdirectories
for root, dirs, files in os.walk(directory):
# Loop through all the files in the current directory
for file in files:
# Check if the file name matches the regular expression
if re.match(fileregex, os.path.join(root, file)):
# If the file is a zip file, use ZipFile to read its contents
if file.endswith('.zip'):
with zipfile.ZipFile(os.path.join(root, file), 'r') as zip_file:
for member in zip_file.namelist():
# Check if the member name (full path) matches the regular expression
if re.match(fileregex, os.path.join(root, file, member)):
with zip_file.open(member) as f:
# Loop through all the lines in the member and check if they match the line regex
for line in f:
if re.search(lineregex, line.decode()):
# If there is a match, print the full path to the file and the matching line
print(os.path.join(root, file, member) + ": " + line.decode().strip())
# If the file is not a zip file, use a regular file read to process its contents
else:
with open(os.path.join(root, file), 'r') as f:
# Loop through all the lines in the file and check if they match the line regex
for line in f:
if re.search(lineregex, line):
# If there is a match, print the full path to the file and the matching line
print(os.path.join(root, file) + ": " + line.strip())
The full directory I paste is "C:\Users\User1\Desktop\Class\proj-2-files.zip\proj-2-files"... Maybe its an issue on my end so feel free to make a .txt doc and try it out.
After my program started printing out nothing I found that sometimes I would get an error (can't remember it on the top of my head) but essentially the directory didn't exist. So I thought I was typing it wrong. I turned the string into a raw string at one point and tried different ways of typing out the directory and still achieved 0 results.
