PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How to convert string values to integer values while reading a CSV file?

 October 17, 2022     csv, int, loops, python, string     No comments   

Issue

When opening a CSV file, the column of integers is being converted to a string value ('1', '23', etc.). What's the best way to loop through to convert these back to integers?

import csv

with open('C:/Python27/testweight.csv', 'rb') as f:
    reader = csv.reader(f)
    rows = [row for row in reader if row[1] > 's']

for row in rows:
    print row

CSV file below:

Account Value
ABC      6
DEF      3
GHI      4
JKL      7

Solution

I think this does what you want:

import csv

with open('C:/Python27/testweight.csv', 'r', newline='') as f:
    reader = csv.reader(f, delimiter='\t')
    header = next(reader)
    rows = [header] + [[row[0], int(row[1])] for row in reader if row]

for row in rows:
    print(row)

Output:

['Account', 'Value']
['ABC', 6]
['DEF', 3]
['GHI', 4]
['JKL', 7]


Answered By - martineau
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing