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

后端 未结 3 1906
你的背包
你的背包 2021-02-19 23:03

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 intege

3条回答
  •  Happy的楠姐
    2021-02-19 23:34

    You could just iterate over all of the rows as follows:

    import csv
    
    with open('testweight.csv', newline='') as f:
        rows = list(csv.reader(f))      # Read all rows into a list
    
    for row in rows[1:]:    # Skip the header row and convert first values to integers
        row[1] = int(row[1])
    
    print(rows)
    

    This would display:

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

    Note: your code is checking for > 's'. This would result in you not getting any rows as numbers would be seen as less than s. If you still use Python 2.x, change the newline='' to 'rb'.

提交回复
热议问题