VRam VRam - 2 months ago 6
Python Question

I'm struggling to write numbers (0-10) into a CSV file. How do I change into a list, convert to integers, and have the number on each line?

Writes numbers from 0 to 10 into a CSV file



import csv

fileW = open('numbers.csv', 'w')
fileW.write('0,')
fileW.write('\n1,')
fileW.write('\n2,')
fileW.write('\n3,')
fileW.write('\n4,')
fileW.write('\n5')
fileW.write('\n6,')
fileW.write('\n7,')
fileW.write('\n8,')
fileW.write('\n9,')
fileW.write('\n10')
fileW.close();


Read the numbers into a list



fileR = open('numbers.csv')
contnts = fileR.read()
print(contents)


This is my code. How do I convert this into integers and change into a list so that when I print the contents I got one column of numbers: one number on each line like [0 on first line, 1 on second line, 2 on third line...]?

Answer

This is a pythonic way to save, obtain the numbers and create a list named int_list with all those integers:

with open('numbers.csv', 'w') as fileW:
    for i in range(11):
        fileW.write('%s\n'%i)

int_list = []
with open('numbers.csv','r') as fileR:
    for line in fileR:
        line = line.rstrip('\n') # read line and clean the EOL
        int_list.append(int(line))
        print(line) 

print(int_list)

Output:

0
1
2
3
4
5
6
7
8
9
10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Now you can operate the list.