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()
  • `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. – interjay Oct 05 '14 at 16:50
  • You should really consider a [`namedtuple`](https://docs.python.org/2/library/collections.html#collections.namedtuple) for this; `book1.length` is much more intuitive than `book1[2]`. – jonrsharpe Oct 05 '14 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. – adecker0033 Oct 05 '14 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. – interjay Oct 05 '14 at 17:08
  • @jonrsharpe Thanks, I didn't know you could do that, that's interesting--I will have to look into that more. – adecker0033 Oct 05 '14 at 17:09
  • @interjay I've added what I've tried – adecker0033 Oct 05 '14 at 17:11

2 Answers2

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.

Beginner
  • 2,643
  • 9
  • 33
  • 51
  • 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. – adecker0033 Oct 05 '14 at 19:49
  • This step is to be used in you `populatebooks()` function. Make sure you return `lines` from that function. – Beginner Oct 05 '14 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? – adecker0033 Oct 05 '14 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 . – Beginner Oct 05 '14 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 – Beginner Oct 05 '14 at 21:32
  • Okay so I've edited the code to reflect the displayAll(arrayBooks) and the populateBooks(). Now, when I select Display All (1) on the menu, I get an error when before it would execute what I had (I only had print text there to test it) But now it doesn't show the text or anything I get error: displayAll() takes exactly 1 argument (0 given) – adecker0033 Oct 05 '14 at 21:57
  • Okay, so I've updated mine, but I'm still getting "Invalid syntax" on the print function in displayAll(arrayBooks). I get "each_entry" highlighted after the word print with that invalid syntax error. It's written exactly as above. Shouldn't I populateBooks() to the arrayBooks? So that information will be stored there. I feel like there's nothing stored in arrayBooks at the moment--but I could be wrong...lol – adecker0033 Oct 05 '14 at 22:33
  • if you are using `Python 3.x` you need to enclose your `print` statements in `( )`. You are parsing the list returned from `populateBooks()` to `displayAll()` in the first `if` statement in `displaybookmenu()` – Beginner Oct 05 '14 at 22:38
  • Omg! That worked! Thank you so much! So now that I know the information is getting pulled from the file and used, how exactly do I access that information? Like I assumed I'd take each line of book information like arrayBooks[0] (for the first book) and put it in another array book1 that has the specs for that book (title, year, pages, author) as the objects of the array so I can use them. I've tried using split on arrayBooks[0] but I get an error...? – adecker0033 Oct 05 '14 at 22:54
  • `arrayBooks[0] ` will give you the first list in the `arrayBooks` list. Since this is not a `tuple`, you cant use tuple unpacking . You will have to use indexes . I wont feed you the entire answer. List indices are very easy to work with. Try this `arrayBooks [0][0]`. Keep putting in different numbers in the 2 brackets and youll know whats happening – Beginner Oct 05 '14 at 23:00
  • I get it, I think. So, arrayBooks[0][2] would give me 152 ---first book, third listing, which is pages numbers. first book has 152 pages. I understand that, Thank you so much! You've been a great help! – adecker0033 Oct 05 '14 at 23:13
-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

Community
  • 1
  • 1
Mabs
  • 1
  • 1
  • For example, if you add: global arrayBooks, it will work. (Why down voting me? trying to help) – Mabs Oct 05 '14 at 17:23
  • And my output for book1 is: ['Animal Farm', '1945', '152', 'George Orwell\n'] – Mabs Oct 05 '14 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! – adecker0033 Oct 05 '14 at 19:43