473,386 Members | 1,752 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

How to read specific item in a list

I have created a list and would like to read specific items in it, I only can read 1

Expand|Select|Wrap|Line Numbers
  1. import cPickle, sys, shelve
  2.  
  3. ## open file that stores scores
  4.  
  5. choice = None
  6. employees = []
  7. while choice != "0":
  8.  
  9.     print \
  10.             """
  11.             411 TUCKSHOP
  12.  
  13.             OPTIONS:
  14.             0 - Exit
  15.             1 - Employee: Add New Employee
  16.             2 - Employee: Display Balance
  17.             3 - Show All Employees and Balances
  18.             4 - Employee: Make deposit
  19.             5 - Purchase items @ Tuck Shop
  20.             6 - Remove all emmployees from database
  21.  
  22.             """
  23.     choice = raw_input("Choice: ")
  24.     print
  25.  
  26.     #exit if choice is "0"
  27.     if choice == "0":
  28.         print "Good bye, please call again..."
  29.  
  30.     #Choice 1 - Add Employees to a file    
  31.     elif choice == "1":
  32.         #Create a sequence
  33.         empnum = int(raw_input("Enter Employee Number: " ))
  34.         name = raw_input("Enter Employee Name:" )
  35.         sname = raw_input("Enter Employee Surname:" )
  36.         dept = raw_input("Enter Department:" )
  37.         bal = float(raw_input("Employee Balance R: "))
  38.         entry = (empnum, name, sname, dept, bal)
  39.         employees.append(entry)
  40.  
  41.         #create pickle file
  42.         pickle_file = open("emp_data.dat", "a+")
  43.         cPickle.dump(entry, pickle_file)
  44.         #close pickle file
  45.         pickle_file.close()
  46.  
  47.         #create a shelve
  48.         #empshelve = shelve.open("emp_data2.da")
  49.         #empshelve ["emp_number"] = [emp_number]
  50.  
  51.         #Ensure sync
  52.         #empshelve.sync()
  53.         #close shelve
  54.         #empshelve.close()
  55.  
  56.     #Choice 2 - Display Balances
  57.     elif choice == "2":
  58.  
  59.         pickle_file = open("emp_data.dat", "r")
  60.         emps = cPickle.load(pickle_file)
  61.         #Prompt user for search
  62.         for entry in employees:
  63.             empnum, name, sname, dept, bal = entry
  64.         print name, "\t", bal
  65.         empn = int(raw_input("\nChoose employee number: "))
  66.  
  67.         print "\nDisplaying Balance\n"
  68.         if empn in emps:
  69.             print "Balance ==> R ", emps[4] 
  70.         else:
  71.             print "Sorry"
  72.         pickle_file.close()
  73.  
Aug 18 '11 #1
7 3483
In Python 3 the print statement is gone, it is replaced by the print function.
http://www.harshj.com/2008/12/09/the...n-in-python-3/
Aug 18 '11 #2
dwblas
626 Expert 512MB
You have to check the first element of the tuple against the entry number:
Expand|Select|Wrap|Line Numbers
  1.         found = False
  2.         for entry in employees:
  3.             if empn == entry[0]:
  4.                 print "Balance ==> R ", entry[4]
  5.                 found = True
  6.         if not found:
  7.             print "Not a valid employee number" 
Generally, a dictionary is used, with the employee number as the key pointing to a list of items http://greenteapress.com/thinkpython/html/book012.html so you can then use, if empn in employee_dict.
Aug 18 '11 #3
dwblas
626 Expert 512MB
A couple of hints:
# 6 is easy --> employees = [] ## re-initialize as an empty list
When adding an employee, check if the number is already in the list, since you don't want the same employee number in the list twice.
Use a function to look up an employee number, since you will be doing this for every choice on the menu.
Use a list instead of a tuple so you can change it (make deposits)
Read the pickle file once, before the while loop, instead of every time through the loop, and write/dump/close it once, after the while loop. Adds will be appended to the list that will be pickled.
Aug 18 '11 #4
All your suggestions have been invaluable and I have gotten someway but when I cPickle the file I fail to read the contents back as a list
Expand|Select|Wrap|Line Numbers
  1. #Choice 2 - Display Balances
  2.     elif choice == "2":
  3.  
  4.         lists = []
  5.         infile = open('emp_data.dat', 'r')
  6.         #inlist = cPickle.load(infile)
  7.         while 1:
  8.             try:
  9.                 lists.append(cPickle.load(infile))
  10.  
  11.             except (EOFError):
  12.                 break
  13.         infile.close()
  14.         #Prompt user for search
  15.         print len(lists)
  16.         empn = int(raw_input("\nChoose employee number: "))
  17.         found = False 
  18.         for entry in lists: 
  19.            if empn == entry[0]: 
  20.                 print "Balance ==> R ", entry[4] 
  21.                 found = True 
  22.         if not found: 
  23.             print "Not a valid employee number"
Aug 26 '11 #5
dwblas
626 Expert 512MB
It should be
lists = cPickle.load(infile)
http://wiki.python.org/moin/UsingPickle
Aug 26 '11 #6
hi dwblas;

I'm really am loosing my mind now. my code is only able to display the first entry, from there my if statement only evaluates to false for all other entries. please correct my code:

#Choice 2 - Display Balances
elif choice == "2":

lists = []
infile = open('emp_data.dat', 'r')
lists = cPickle.load(infile)

empn = int(raw_input("\nChoose employee number: "))
found = False
for entry in lists:
if empn == entry[0]:
print "Balance ==> R ", entry[4]
found = True
if not found:
print "Not a valid employee number"
infile.close()
Aug 28 '11 #7
dwblas
626 Expert 512MB
The pickle statement is still wrong. The link in my previous post shows an example of pickling and unpickling. If you are not going to read the post then there is little reason to post. Also, for future problems add a print statement. In this case:
Expand|Select|Wrap|Line Numbers
  1. for entry in lists:
  2.     print "testing" empn, entry[0]
  3.     if empn == entry[0]: 
please correct my code
That's just rude.
Aug 28 '11 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: lokb | last post by:
Hi, I have a C function fread which does reading of multiple items as num = fread(code,1,ilen-4,ifile); which is reading 1 byte information ilen-4 times and updating to code and returns a...
4
by: theo | last post by:
Program flow...load file,then extract the xml text tags from the file,then the number of Xml tags retrieved from the file determines the number of dropdownlist controls instanciated in the...
2
by: JP | last post by:
Hi, I am trying to loop through the listbox and read the selected items from the list, within a CLICK event on an aspx page. The following is what I have tried. It loops through the listbox,...
11
by: Madison Kelly | last post by:
Hi all, I am new to the list and I didn't want to seem rude at all so I wanted to ask if this was okay first. I have a program I have written in perl which uses a postgresSQL database as the...
1
by: Esmail Bonakarian | last post by:
Greetings all, What is the best way to access specific records in an Excel file? I have an Excel file, I want to randomly and repeatedly (maybe around up to 50 times) draw some rows of data...
12
by: Chris | last post by:
Are there any other controls which could replace List & Tree controls, because they have limitation of accepting only 32767 items. thanks a lot in advance.
5
by: Johnymap | last post by:
Hi everyone I have text file which looks like these: "index.txt" Johan 22 sebaya "home.hml" Mpho 23 leboa "index.frt" Tedesca 24 teba My problem is i want to read the number on the last...
1
by: KrazyKasper | last post by:
Access 2003 – Multi-Column List Box – Select Multiple Items I have a multi-column (3 columns) list box that works well to select one set of records or all sets of records (based on the first field...
3
by: Lu5ck | last post by:
Hi all, How do you read specific div id in a external html returned from resposnetext? Also, is it possible to count how many div tag are there in the resposnetext? Been googling and can't...
0
by: =?ISO-8859-1?Q?Ricardo_Ar=E1oz?= | last post by:
ajak_yahoo wrote: Check Paul McNett's article in FoxTalk "Exploring Python from a Visual Foxpro Perspective" and check the code in : http://www.paulmcnett.com/vfp/09MCNESC.zip HTH
0
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,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
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...
0
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...
0
BarryA
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...
0
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.