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!")
-
arrayBooks = populateBooks()
-
displayBookMenu()
-
-
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():
-
-
def displayShortest():
-
-
def displayLongest():
-
-
def displayOldest():
-
-
def displayNewest():
-
-
-
main()
3 1661
You can simply use the return from readlines() and split the record when required. - test_text="""Animal Farm,1945,152,George Orwell
-
To Kill A Mockingbird,1960,324,Harper Lee
-
Pride and Prejudice,1813,279,Jane Austen and Anna Quindlen
-
"""
-
with open("./bookfile.txt", "w") as fp_out:
-
fp_out.write(test_text)
-
-
book_data=open("./bookfile.txt", "r").readlines()
-
book_data_1=book_data[1].split(",")
-
book_data_2=book_data[2].split(",")
-
print book_data_1[2], book_data_2[2]
-
print book_data_1[2] == book_data_2[2]
To place into an array you would append the split record - book_data=open("./bookfile.txt", "r").readlines()
-
-
## to array
-
test_array=[]
-
for rec in book_data:
-
test_array.append(rec.strip().split(","))
-
print "\n", test_array
-
print test_array[1][2], test_array[2][2]
-
print test_array[1][2]==test_array[2][2]
Thank you! I've tried a few things and got the file to open and display all, I'm having a hard time using the individual information from the lines pulled.
Here's what I have now: - def displayBookMenu():
-
print("\n1: Display All Books")
-
print("2: Display Shortest")
-
print("3: Display Longest")
-
print("4: Display Oldest")
-
print("5: Display Newest")
-
print("0: Quit")
-
choice = int(input("Choice: "))
-
-
if choice==1:
-
displayAll(populateBooks())
-
elif choice==2:
-
displayShortest(arrayBooks)
-
elif choice==3:
-
pass
-
elif choice==4:
-
pass
-
elif choice==5:
-
pass
-
elif choice==6:
-
pass
-
elif choice==0:
-
exit()
-
else:
-
print("Invalid input, please try again.")
-
-
-
-
def populateBooks():
-
lines = [line.strip().split(',') for line in open("bookfile.txt")]
-
return lines
-
-
-
-
def displayAll(arrayBooks):
-
print("\nAll Books: \n")
-
for books in arrayBooks:
-
for each_entry in books:
-
print (each_entry),
-
print
-
-
-
def displayShortest():
-
list1=[arrayBooks[0][2],arrayBooks[1][2],arrayBooks[2][2]]
-
print("Shortest Book: ", min(list1))
-
-
-
def main():
-
print("Welcome!")
-
displayBookMenu()
-
populateBooks()
-
arrayBooks = populateBooks()
-
#end main
-
-
main()
I've got it to display all the Books, but when I try to put the pages in a list to find the min, I get errors about the list/arrayBooks
The only function in the program that is aware of the return, "lines", is here - if choice==1:
-
displayAll(populateBooks())
None of the other functions in the program know about the file read. You should be using a class for this program as you can eliminate those problems easily.
For option #2, arrayBooks is not known by this function, only the main() function knows about it, see here for info on passing parameters. - elif choice==2:
-
displayShortest(arrayBooks)
a work-around is - def displayBookMenu(arrayBooks):
-
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(arrayBooks) ## passed to the function
-
...
-
etc.
-
-
print("Welcome!")
-
arrayBooks = populateBooks() ## catches the return
-
displayBookMenu(arrayBooks) ## passes the array to the function
Finally, I would suggest that you include some test book in the file with 99 pages, as it won't print the min that you think it would because you are using strings (evaluates left to right), not integers. - print min(["99", "250", "1001"])
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Steven Bethard |
last post by:
Here's what I'm doing:
>>> lst =
>>> splits =
>>> for s in lst:
.... pair = s.split(':')
.... if len(pair) != 2:
.... pair.append(None)
.... splits.append(pair)
....
|
by: Jeremy Sanders |
last post by:
I have a large string containing lines of text separated by '\n'. I'm
currently using text.splitlines(True) to break the text into lines, and
I'm iterating over the resulting list.
This is very...
|
by: Aaron Walker |
last post by:
I have a feeling this going to end up being something so stupid, but
right now I'm confused as hell.
I'm trying to code a function, that given a string and a delimiter char,
returns a vector of...
|
by: vladislavf |
last post by:
Hi All,
I need to pass array of strings from C++/CLI to unmanaged C++ function.
(The unmanaged API signatire is : int Combine(int NumOfInputFiles,
wchar_t **names) and I want to call it from...
|
by: Jared.Holsopple |
last post by:
Hi all,
I have a dynamically allocated array of doubles in VC++ .NET. When I
view the array in the watch window with "arrayName, 10", it displays
the correct value for arrayName, but arrayName...
|
by: r035198x |
last post by:
Breaking up a string
Instead of using the old StringTokenizer class, a simple trick is to use the String.split method.
String string = "This is a string";
String tokens = string.split("...
|
by: pereges |
last post by:
I've an array :
{100,20, -45 -345, -2 120, 64, 99, 20, 15, 0, 1, 25}
I want to split it into two different arrays such that every number <=
50 goes into left array and every number 50 goes...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |