1

I'm writing a script in Python 3.8.5 where the user needs to input a string, called guid in my database, and TinyDB will print back the filename value for the same upload, but I can't for the life of me figure out how to print just the filename key so that os.remove can delete the file with the matching file name. I've already tried the solution on How to retrieve a single value from a TinyDB database? but I couldn't get it to work in my code.

The database:

{
"_default": {
    "11": {
        "upload_time": "17/Aug/2020 13:39:30",
        "uploader_ip": "127.0.0.1",
        "guid": "ORcjzt96PB3jQ7xtytxe",
        "token": "test_123",
        "filename": "RPADeQ.txt",
        "filetype": "application/x-www-form-urlencoded"
    }
}

}

The code

fileForDel = input("Input file's GUID: ")
print(log.search(file.guid == str(fileForDel)))
confirm = input("Delete this file? (y/n)")
log.remove(file.guid == fileForDel)
print("Deleted the file successfully!")

Pseudo-code

output = log.search(file.guid == str(fileForDel))
os.remove(output["filename"])

Thanks.

Joshua
  • 11
  • 2

1 Answers1

0

log.search(...) returns always a list of documents, not a single document if the query matches only one entry.

You could work with the search result like this, if you're sure that there is exactly one result, otherwise you need some error handling:

# Access the first element in the list
output = log.search(file.guid == str(fileForDel))[0]

# Or unpack the list directly
[output] = log.search(file.guid == str(fileForDel))

# Remove the file and the database entry
os.remove(output["filename"])
log.remove(file.guid == str(fileForDel))
timo.rieber
  • 3,727
  • 3
  • 32
  • 47