Reputation: 11
I have a text file, "blah.txt" and within it contains this data:
blah1: [01,02,03]
blah2: [01,02,03]
I can read through the file and put it into a list with this:
reader = csv.reader(open('blah.txt'),delimiter=":")
But [01,02,03] isn't recognized as a list, but as a string. Is there a short and simple way to make it so that it does recognize it as a list?
Full code:
import csv, operator
reader = csv.reader(open('file.txt'),delimiter=":")
sortedlist = sorted(reader, reverse=True)
for name, score in sortedlist:
print(score)
Edit:
I can instead write the data as
blah1:010203
blah2:010203
and use this:
import csv, operator
reader = csv.reader(open('file.txt'),delimiter=":")
sortedlist = sorted(reader, reverse=True)
for name, score in sortedlist:
score = [int(score[i:i+2]) for i in range(0, len(score), 2)]
print(name, score)
However it isn't convenient to read from the text file directly (by person).
Upvotes: 1
Views: 56
Reputation: 11
This is what I ended up using, thanks @timgeb for the suggestion.
reader = csv.reader(open(file + '.txt'),delimiter=":")
data = {}
for name, score in reader:
data[name] = sorted(ast.literal_eval(score), reverse=True)
Upvotes: 0
Reputation: 2677
The input (line.txt):
blah1: [01,02,03]
blah2: [01,02,03]
blah3: [01,02,03]
blah4: [01,02,03]
Process the file:
from collections import OrderedDict # if you want to maintain the order
data = OrderedDict()
for line in open("list.txt").readlines():
k, v = line.split(':')
# from list (in string form), remove whitespace, remove brackets
# turn the list (in string form) into a list
data[k] = v.strip()[1:-1].split(',')
The result:
>>> data
OrderedDict([('blah1', ['01', '02', '03']), ('blah2', ['01', '02', '03']),
('blah3', ['01', '02', '03']), ('blah4', ['01', '02', '03'])])
Upvotes: 0
Reputation: 78750
At first I thought ast.literal_eval
was the right tool for this, but look what happens:
>>> literal_eval('[01,020,03]')
[1, 16, 3]
Since you probably don't want integers starting with zero to be interpreted in base 8, I don't think there's a much prettier solution than to split by comma:
>>> s = '[01,020,03]'
>>> [int(x) for x in s[1:-1].split(',')]
[1, 20, 3]
If you have a chance to write your integers without leading zeros to your file, ast.literal_eval
wins again.
Upvotes: 1
Reputation: 2162
Say you have "[01,02,03]"
stored as a string variable s
. You can then do:
score = [int(x) for x in s.strip('[').strip(']').split(',')]
as long as there are no spaces in between the brackets.
Upvotes: 0