pythonlinear-search

Is there a way to choose and open a text file from a dictionary in Python?


I'm currently writing a program that displays a set of guitar chords in TAB using turtle and I was wondering to save me writing out many nested if statements, if it would instead be possible to instead use text files with the numerical data inside and then store the names of the text files in a dictionary in python like so:

d = {0: "", 1: "Am.txt", 2: "Bm.txt", 3: "Cm.txt", 4: "Dm.txt", 5: "Em.txt", 6: "Fm.txt", 7: "Gm.txt"}
l = [0,1,2,3,4,5,6,7]

My aim was to then use a sequential search to identify which test file to open based off of the user input using this:

n = 0
penup()
T.color('white')
x = 0

while x != 1: # this while loop is redundant
    N = 0
    chord = int(input("Please choose a number for your chord"))
    # compare input with dictionary values
    while N != 2:
        if(chord == l[n]):
            f = open(d[n])
            while True:
                N2 = f.readline()
                if not N2:
                    break
        if(chord != l[n]):
            n = n + 1
    
        N = N + 1
    x = x + 1


My code past this is just the commands telling the turtle how to move and write the text from the file with N2. So far my result has just been printing "Am.txt" instead of the content in that text file with no error messages following it. My previous code to this was to just manually write out everything with if statements but that seemed needless to me if I could make this work.


Solution

  • I assume you are new to coding? The benefit of dictonaries is that you can directly access the values by their keys. Also be careful with while True loops, as they create infinite loops... Also in your case the user needs to know which number is what chord. Why not make the keys more specific. Also read about opening and reading files. Try this for now, but be aware you have to be in the directory where the Am.txt and Bm.txt are located (absolute vs relative path).

    d = {0: "", 'Am': "Am.txt", 'Bm': 'Bm.txt'}
    
    
    while True:
        chord = input('Input Chord: ')
        if chord in d:
            with open(d[chord], 'r') as f:
                lines = f.readlines()
    
            for line in lines:
                print(line)
        else:
            print('chord not found')