Search code examples
pythonpython-3.xlistdisk

How to read and edit a list from disk in Python 3?


I have a list of dictionaries that I want to append to a separate disk file. Then, I want to be able to read this list of dictionary items and move them to other lists, in different files.

import os

# List 'x' will auto-populate itself with hundreds of new dictionary items upon run - using x.append({'name': f'{var}', 'job': f'{var2}'}) etc.

x = []

i = input('Request: ')

if i == 'add to list':
    with open('example list', 'a') as list:
        list.write(x)
elif i == 'print list':
    with open('example list', 'r') as list:
        list.read(x)
        print(list)

# in this next block, I would like to be able to move an item from the 'example list' list to a different list that is housed in a separate file

elif i == 'move item':
    # 'n' requests an integer value to represent the index in the list
    n = input('Which item do you want to move? ')
    with open('example list', 'r') as list:
        j = list[n]
        # I want to delete 'j' from 'example list' 
    with open('other list', 'a') as other_list:
        # I want to append 'j' to 'other list'
        other_list.write(j)

print('example list')

I am stuck on reading and moving these list items. I can't even get it to print "example list" in a nice format.

I have heard of pickle module, but I've never used it. I also understand that it may be necessary to save these lists as json files in order to be able to access the list items and the subsequent dictionary keys within.


Solution

  • I figured it out. Using the json module I was able to dump the list to an external json file with:

    x = []
    
    with open('json list.json', 'w') as f:
        json.dump(x, f)
    

    I could then load the data back in with:

    list1 = open('json list', 'r')
    listread = list1.read()
    data = json.loads(listread)
    

    For moving items between lists I used this:

    move_item = data[3]
    del move_item
    json.dumps(data)
    move_to = open('other list'. 'a')
    move_to.write(move_item)
    list1.close()
    move_to.close()
    

    Once loaded, the list and subsequent dictionaries within remain intact as their respective objects, thus allowing for access via index or key. Thank you to everyone, I used a combo of everyone's suggestions.