Talha Farrukh Talha Farrukh - 1 year ago 63
Python Question

Searching through index number in a .txt file (JSON format) in Python code

I am a newbie to python and having some difficulties in programming. I have to search through the index number in a data.txt file and then delete the whole item according to the input of the user. My code is as follows:

if option == 'd':
if 'name' in open('data.txt').read():
ind = int (input ("Menu item number to delete: "))
with open ('data.txt') as data_file:
data = json.load(data_file)
if ind in data[ind]:
del data[ind]
json.dump(data, open('data.txt', 'w'))
print ('Menu item deleted.\n')
print ('No such items exist')
print ('There are no menu items saved')

For e.g. if the user enters the 3, the 3rd item will be deleted. The code is working fine but I also have to find that whether the user entered index exists in the file or not and I am having errors in that through the command if ind in data[ind]: The error is shown below:

File "D:/R/043/N.py", line 41, in inputSomething
if ind in data[ind]:
IndexError: list index out of range

Immediate help will be appreciated.

Answer Source


Based on the json you posted, you're loading an array rather than an object that's indexed by keys, so if you want to delete a specific item from the array, you would first need to check that it contains at least the number of items selected, then delete that item -- something like this:

EDIT: It is strange that you would expect your user to enter '0' for the first item in a menu, something like this would work:

        if len(data)-1 >= ind:
            del data[ind]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download