0

So, I'm trying to take information from bookfile.txt and display information from it. So far, I've opened the file. I'm having trouble getting each line as one object of arrayBooks.

I'd like to have arrayBooks[0]="Animal Farm,1945,152,George Orwell"

Then, I'm going to use book1 = arrayBooks[0].split(',') to split it to other information, such as:

  book1[0]="Animal Farm"
  book1[1]=1945
  book1[2]=152
  book1[3]="George Orwell"

So, when I want to find the shortest book, I can compare book1[2] to book2[2] and book3[2] to do so.

My main problem is getting the information in the array and usable. Anything I've tried doesn't seem to work and gives an error in the displayAll() function.

I'm using the displayAll() as a control because I feel if I can get the information to display, I will have it to use.


bookfile.txt:

Animal Farm,1945,152,George Orwell

To Kill A Mockingbird,1960,324,Harper Lee

Pride and Prejudice,1813,279,Jane Austen and Anna Quindlen


 def main():
      print("Welcome!")
      displayBookMenu()
      populateBooks()
      displayAll(populateBooks())

 def displayBookMenu:
      print("\n1: Display All Books")
      print("2: Display Shortest Book")
      print("3: Display Longest Book")
      print("3: Display Oldest Book")
      print("4: Display Newest Book")
      print("0: End")
      choice = int(input("Choice: "))

      if choice == 1:
           displayAll()
      elif choice == 2:
           displayShortest()
      elif choice == 3: 
            displayLongest()
      elif choice == 4: 
           displayOldest()
      elif choice == 5:
           displayNewest()
      elif choice == 0:
           exit()
      else:
           print("Invalid Input")

 def populateBooks():
      fp = open("bookfile.txt", "r")
      return fp.readlines()

 def displayAll(arrayBooks):
      print ("\nAll Books: \n")
      #THIS IS WHERE I GET ERROR vvv
      print arrayBooks[0]


 def displayShortest():

 def displayLongest():

 def displayOldest():

 def displayNewest():


 main()
6
  • displayAll() doesn't have any code in it, so it makes sense that it gives you an error. Assuming that it does have some code in it, you need to show both the code and the error you get. Commented Oct 5, 2014 at 16:50
  • You should really consider a namedtuple for this; book1.length is much more intuitive than book1[2]. Commented Oct 5, 2014 at 16:56
  • @interjay I've taken the code out because anything I've tried just gives me an error pointing to displayAll(). I've tried printing the arrayBooks[1] as a string and it gives me an error. Not sure if I need to include something else to get the books and their information displayed other than trying to display where they are located. Commented Oct 5, 2014 at 17:07
  • You need to show code that demonstrates the error. Ideally you would take out everything irrelevant such as the menu, but the code causing the error itself is crucial. Commented Oct 5, 2014 at 17:08
  • @jonrsharpe Thanks, I didn't know you could do that, that's interesting--I will have to look into that more. Commented Oct 5, 2014 at 17:09

2 Answers 2

0

try this:

lines = [line.strip().split(',') for line in open("books.txt")]

Using list comprehesions you can read your file into a list named lines and convert each line from your files into a list of lists.

These are the results i got when i ran it:

`lines = [line.strip().split(',') for line in open("books.txt")]

print lines
print lines[2]
print lines [2][1]`
enter code here

[['Animal Farm', '1945', '152', 'George Orwell'], ['To Kill A Mockingbird', '1960', '324', 'Harper Lee'], ['Pride and Prejudice', '1813', '279', 'Jane Austen and Anna Quindlen']]
['Pride and Prejudice', '1813', '279', 'Jane Austen and Anna Quindlen']
1813

Now there are a number of edits. Here. Make sure you looks at them carefully:

`def displayBookMenu():
      print("\n1: Display All Books")
      print("2: Display Shortest Book")
      print("3: Display Longest Book")
      print("3: Display Oldest Book")
      print("4: Display Newest Book")
      print("0: End")
      choice = int(input("Choice: "))

      if choice == 1:
           displayAll(populateBooks())
      elif choice == 2:
           displayShortest()
      elif choice == 3: 
            displayLongest()
      elif choice == 4: 
           displayOldest()
      elif choice == 5:
           displayNewest()
      elif choice == 0:
           exit()
      else:
           print("Invalid Input")

def populateBooks():
      lines = [line.strip().split(',') for line in open("books.txt")]
      return lines

def displayAll(arrayBooks):
      print ("\nAll Books: \n")
      #THIS IS WHERE I GET ERROR vvv
      for books in arrayBooks:
            for each_entry in books:
                  print each_entry,
            print

def displayShortest():
      pass
def displayLongest():
      pass
def displayOldest():
      pass
def displayNewest():
      pass

def main():
      print("Welcome!")
      displayBookMenu()
      populateBooks()
main()

Remove displayBooks(populateBooks()) and instead have it in you if choice ==1 statement.

11
  • Okay, so I tried that in the displayAll() and the populateMovies() to try to just get those lines into a list to be used, but I get an error after the print. I've tried print lines and print arrayBooks. I also moved arrayBooks to global scale. Commented Oct 5, 2014 at 19:49
  • This step is to be used in you populatebooks() function. Make sure you return lines from that function. Commented Oct 5, 2014 at 21:05
  • Awesome, I got no errors there, but when I put the print function in displayAll(), I get an error for whatever I used after print. I've tried print lines[0] and print arrayBooks[0] to attempt to print the first book information but it takes me to either "lines" or "arrayBooks" as the error? Commented Oct 5, 2014 at 21:18
  • That is because the list you created from your file is local to that function. Change displayall() to displayall(booklist). This means you are passing an argument to the function. Inside the displayall(booklist) function add this arrayBooks = populatebooks(). This means the list returned from the populatebooks function is not stored in a variable arrayBooks inside the displayall() function . Commented Oct 5, 2014 at 21:24
  • Ignore the above comment. It is so wrong, i am ashamed I even though about it. Do this instead:Change displayall() to displayall(arrayBooks). This means you are passing an argument to the function. Outside both functions , in your main() function, add this populateBooks() displayAll(populateBooks()). Both these statements need to be on a different line. The comments sections dsnt allow well formatted code to be placed Commented Oct 5, 2014 at 21:32
-1

First, you have an error in

def displayBookMenu: #needs ()

And you can't read ArrayBooks because it'a not a global (or nonlocal) variable. I think you have problems with variable scope. Check this: Python variable scope error

3
  • For example, if you add: global arrayBooks, it will work. (Why down voting me? trying to help) Commented Oct 5, 2014 at 17:23
  • And my output for book1 is: ['Animal Farm', '1945', '152', 'George Orwell\n'] Commented Oct 5, 2014 at 17:29
  • I didn't down vote you. And I have the () in my code, I'm using two separate computers to do this and had to retype my code on this computer, typo - sorry. I'll look into the scopes - thank you! Commented Oct 5, 2014 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.