VRam - 1 month ago 5x
Python Question

# 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')
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...]?

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.