Reputation:
Write a function named "file_to_int_list" that takes no parameters and returns a list of integers. The function will read a file named "continued.txt" and returns the contents of the file in an array with each line of the file as a separate values in the data structure. You must convert each line to an integer and you can assume each line is a well-formed integer. (My code below)
def file_to_int_list():
with open("continued.txt", 'r') as f:
content = f.read()
return content.split(',')
I am getting the returned value as ['12\n2\n4\n7\n17\n1\n-2\n'] when I input in the values from continued.txt. How do I get the input as [12, 2, 4, 7, 17, 1, -2]?
Upvotes: 0
Views: 363
Reputation: 61900
You need to iterate over each line and convert it to integer:
def file_to_int_list():
result = []
with open("continued.txt", 'r') as f:
for line in f:
result.append(int(line))
return result
Upvotes: 1