-4

I'm trying to make this code turn the prodname variable into an int value:

def prod_check(dirname):
    prodname_to_prodnum = {}
    fid2 = open('sample.txt','r')
    line = fid2.readline()
    line = line.strip()
    pline = line.split(',')
    prodname = (pline[0])[1:-1]
    prodnum = prodname
    prodname_to_prodnum[prodname] = prodnum
    line = fid2.readline()
    fid2.close()

but when I used "int(prodname)" I get an error

Ferdinand
  • 241
  • 3
  • 12
  • 1
    Where exactly are you trying to do `int(prodname)` and what is the value of `prodname`? – mgilson Jul 18 '12 at 20:28
  • 1
    aaaand what's the error? – Colin Dunklau Jul 18 '12 at 20:28
  • trying to make to integer where it says "prodnum=prodname" but like i said I tried "int()" but no luck. The error is "Value error: invalid literal for int<> with vase 10: 'James Sakolov'" Prodname is a string of a number. – Ferdinand Jul 18 '12 at 20:32
  • 3
    *blink* .. what number would you like "James Sakolov" to become? `prodname` isn't a string of a number, it's apparently a string of a name. – DSM Jul 18 '12 at 20:34
  • @Larson "Prodname is a string of a number" -- is it guaranteed to be an integer? or could it be a string like "15.0" ? If that's the case then you'll need `int(float(prodname))` – mgilson Jul 18 '12 at 20:35
  • It looks like you are processing csv data. Maybe you should use the csv module? – Marco de Wit Jul 18 '12 at 20:36
  • that was my mistake with that name its actually numbers "1,2,3,4,..." random order. But the number format is always between 1-999 – Ferdinand Jul 18 '12 at 20:36
  • So it is a string containing lots of numbers? Then you want `map(int,prodname.split(','))` – mgilson Jul 18 '12 at 20:38
  • What it is are lines being pulled from a file as you see, the format for them is: #,"Name","Last", "Name", "Date", I pull the first value from it and want it as an integer. – Ferdinand Jul 18 '12 at 20:38
  • maybe you want `pline[0]` then? – mgilson Jul 18 '12 at 20:58
  • yes that was a typo sorry to confuse you guys. – Ferdinand Jul 18 '12 at 20:59

2 Answers2

1

Try this instead of prodnum = prodname:

try:
  prodnum = int(prodname)
except ValueError:
  prodnum = None
  print('prodname = ',prodname)
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Marco de Wit
  • 2,686
  • 18
  • 22
1

Lists in Python are 0-based, not 1-based. You've already broken the line into fields with split, so you should use prodnum = int(pline[0]) to get the first field.

Edit: I wish people would use copy/paste to put their code into the question, typos make all the difference.

I don't know why you're removing the first and last character from the number field, perhaps because you need to strip blanks from it? If so, try using prodnum = int(pline[0].strip()).

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622