So I'm trying to make a file searcher just to make it easier for myself regarding all the files with info I have, I've gotten to the part where it can extract the file but then
I've tried using json.loads() but get TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper
and when I use json.load() I get TypeError: list indices must be integers or slices, not str
here is my code:
class fileSearcher:
def __init__(self):
self.directory = "my directory"
self.word = str(input(f'Input the word you want to search for: '))
if self.word != "":
self.main()
else:
fileSearcher()
def main(self):
for subdir, dirs, files in os.walk(self.directory):
for file in files:
filepath = subdir os.sep file
for ft in ".zip":
if ft in filepath:
archive = ZipFile(filepath)
for file2 in archive.namelist():
if file2.__contains__("https"):
with ZipFile(filepath, 'r') as zip:
zip.extract(file2,os.getcwd())
f = open(file2)
data = json.load(open(file2))
for i in data['url']:
if i.__contains__(self.word):
with open("file", "w ")as f:
f.write(f"{self.word}: {data['url']}")
if __name__ == "__main__":
fileSearcher()
CodePudding user response:
do
for i in data:
if self.word in i["url"]:
instead of data['url']
check out similar question like this for a better answer and in this case you want to be using json.load()
The json.load() is used to read the JSON document from file and the json.loads() is used to convert the JSON String document into the Python dictionary.
CodePudding user response:
The file2 should contains a list
not a dict
that's why.
In addition, you might have a bug in your code. You wrote:
for ft in ".zip":
if ft in filepath:
I think you wanted:
if ".zip" in filepath
Also, to have a cleaner code, you can look at Glob library
Edit:
Same here:
if i.__contains__(self.word):
You should not use __contains__
because it's a dunder method.
you can do:
if self.word in i: