Human Generic
Human Generic

Reputation: 35

Python reading a text file and loading a pre made array/list

I am trying to create a program in python that will take a pre made selection of lists from a file and convert them into a variable.

My current code for this is

datain = open("test.json", "r") #open file storing questions and awnsers
datause = datain.readlines() #get data loaded for use

which is later followed by

for i in range(0, numquest):
    x = []
    print("Question " + str(( i + 1 )))
    x = datause[i]
    print(x[1])
    awns = input(x[2])

Which returns

"
W

The content of my file that i'm reading from is

["What type of device is a mouse? : ", "1) Input 2) Storage 3) Output :", "1", "1) Input"]

Which is what i would like to load as a list/array

["What type of device is a mouse? : ", "1) Input 2) Storage 3) Output :", "1", "1) Input"]
["What type of storage is a hard drive? : ", "1) Optical 2) Magnetic 3) Read-Only : ", "2", "2) Magnetic"]
["How is eight(8) represented in binary? : ", "1) 1111 2) 1001 3) 1000 : ", "3", "3) 1000"]

are the example questions i am currently using for testing in my test.json file

Upvotes: 0

Views: 189

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90889

When you do print(x[1]) , it only prints the character at index 1 , I do not think that is what you want.

If what you want is to print the first element of the list first and then in input(x[2]) you want the second element of the list.

Like myershustinc said, use json.load() to load the data into datause object, and then iterate through each list in datause , and then print first and second element for it.

Example -

for l in datause:
    for i in range(0, numquest):
        print("Question " + str(( i + 1 )))
        print(l[0])
        awns = input(l[1])

I do not think you need x . Also, please note python is 0 indexed, 0 -> index of first element.

Also, seems like your json file is corrupted, try with this content -

[["What type of device is a mouse? : ", "1) Input 2) Storage 3) Output :", "1", "1) Input"],
["What type of storage is a hard drive? : ", "1) Optical 2) Magnetic 3) Read-Only : ", "2", "2) Magnetic"],
["How is eight(8) represented in binary? : ", "1) 1111 2) 1001 3) 1000 : ", "3", "3) 1000"]]

Upvotes: 0

myersjustinc
myersjustinc

Reputation: 714

For a JSON file, you could just use json.load:

import json
with open("test.json", "r") as datain:
    datause = json.load(datain)

At this point datause is an array containing whatever was in your JSON file.

More on the json library in the Python docs.

Upvotes: 2

Related Questions