0

I have a sample file called 'scores.txt' which holds the following values:

10,0,6,3,7,4

I want to be able to somehow take each value from the line, and append it to a list so that it becomes sampleList = [10,0,6,3,7,4].

I have tried doing this using the following code below,

score_list = []

opener = open('scores.txt','r')

for i in opener:
    score_list.append(i)

print (score_list)

which partially works, but for some reason, it doesn't do it properly. It just sticks all the values into one index instead of separate indexes. How can I make it so all the values get put into their own separate index?

1

3 Answers 3

3

You have CSV data (comma separated). Easiest is to use the csv module:

import csv

all_values = []

with open('scores.txt', newline='') as infile:
    reader = csv.reader(infile)
    for row in reader:
        all_values.extend(row)

Otherwise, split the values. Each line you read is a string with the ',' character between the digits:

all_values = []

with open('scores.txt', newline='') as infile:
    for line in infile:
        all_values.extend(line.strip().split(','))

Either way, all_values ends up with a list of strings. If all your values are only consisting of digits, you could convert these to integers:

all_values.extend(map(int, row))

or

all_values.extend(map(int, line.strip().split(',')))
Sign up to request clarification or add additional context in comments.

2 Comments

Using the first solution that you provided gives me a Line 13 in reader = csv(infile): TypeError: 'module' object is not callable error. Do you know why that may be?
@TeeKayM: because I'm a numpty and forgot the .reader part.
3

That is an efficient way how to do that without using any external package:

with open('tmp.txt','r') as f:
    score_list = f.readline().rstrip().split(",")

# Convert to list of int
score_list = [int(v) for v in score_list]

print score_list

2 Comments

Definitely helpful. Can I just ask: What does the '.rstrip()' and '.split() ' functions do? Thanks
Sure, rstrip function removes line endings and split(",") separates a string on ","
2

Just use split on comma on each line and add the returned list to your score_list, like below:

opener = open('scores.txt','r')
score_list = []

for line in opener:
    score_list.extend(map(int,line.rstrip().split(',')))

print( score_list )

2 Comments

You should really use score_list.extend() or use score_list += to avoid creating new lists all the time.
@MartijnPieters Thanks. Updated my answer to use extend

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.