简体   繁体   中英

Extracting integers from a mixed list

I am trying to read from a csv file, extract some values and copy them to an already existing file.

The rows in my file look like this:

row = ['success', '9358', 'MC', '9363.0', 'MC', '1.001', '9363.0', 'MC', '1.001']

I am trying to extract the integer value 9358 and I have tried following things:

  1. int(row[1])
  2. map(int, row[1])
  3. map(int, row['1'])
  4. int(row[1].replace("'", ""))

The error for int(row[1]) is:

Traceback (most recent call last):
  File "upv_c.py", line 26, in
    num1 = int(row[1])
      ValueError: invalid literal for int() with base 10: ''

But every one of these throws some error or the other. Any idea how can I go about it?

My code is as follows:

#!/home/utils/Python-2.7/bin/python2.7
import csv
import xlwt
import xlrd
from xlutils.copy import copy
book = xlrd.open_workbook('reg_test.xls')
wb = copy(book) # a writable copy 
w_sheet = wb.get_sheet(0)
with open('results2.csv', 'r') as f:
    reader = csv.reader(f)
    next(reader, None)
    next(reader, None)
    next(reader, None)
    next(reader, None)
    i = 1
    for row in reader:
        num = map(int, row[1])
        w_sheet.write(i, 2, num)
        i += 1
wb.save('reg_test.xls')

What error you getting exactly ? you should not get an error if you trying to convert a actual number string. Try a try catch block to see what's happening.

try:
for row in reader:
    num = map(int, row[5])
    w_sheet.write(i, 2, num)
    i += 1
except Exception, e:
    print 'Unable to convert', row[5]

Have you tried:

if row.isnumeric():
    my_var = int(row)

This way you can ensure that your string argument is in fact numeric before passing it to int() .

I see your number is enclosed in '' like '123' and when you are trying to read in python it is read as "'123'" in a variable

temp=row[1].replace("'","")

then

num = int(temp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM