简体   繁体   中英

I'm having trouble trying to read the numbers (0 - 10) into a list in Python 3 using CSV file and in a column format.

I first wrote the numbers in a column into a CSV file but having trouble with the reading part. I want to make into one list and make sure that the numbers are converted into ints

f = open('numbers.csv', 'r')
with f:
    reader = csv.reader(f)
    for column in reader:
        print(column)

This is what I wrote for my code and here is my output but how do I make it into a list and convert the numbers into integers?

Column:

['0']
['1']
['2']
['3']
['4']
['5']
['6']
['7']
['8']
['9']
['10']
numlist = list()
f = open('numbers.csv', 'r')
with f:
    reader = csv.reader(f)
    for column in reader:
        numlist.append( int(column[0]) )
print( numlist )

You just need to iterate over each row in your file , cast the first column to int using int() and then add to a list . Here is compact version:

with open('numbers.csv', 'r') as numbers_file:
    reader = csv.reader(numbers_file)
    int_list = [int(row[0]) for row in reader]

print int_list

EDIT :

If you want a column list or nested list, just loop over both columns and rows for the general case:

int_list = [[int(col) for col in row] for row in reader]

or in your particular case where you just want the first/only element of each row, just cast the element to a list :

int_list = [[int(row[0])] for row in reader]

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