Reputation: 21
My question about Python. I have a txt file as:
[1,2,3,4,5]
[6,7,8,9,10]
[11,12,13,14,15]
[16,17,18,19,20]
[21,22,23,24,25]
Every list here is a new line in the file. I want to read the file line by line, however every line should be python list, in other words, if i write for example print list1[0] for first line, list[0] must give 1. When I write the following code: The result is just the character "[". This means that content is not a list. How can I obtain list[0] as it gives 1 ?
#!/usr/bin/python
# -*- coding: utf 8 -*-
import os
import sys
import math
import matplotlib
with open("grafik.txt") as f:
list = f.read()
print list[0]
if __name__ == "__main__":
pass
Upvotes: 2
Views: 661
Reputation: 174706
You could do like this also.
with open('file') as f:
fil = f.readlines()
m = (line.replace('[', '').replace(']', '').strip().split(',') for line in fil)
for line in m:
print(line)
OR
import re
with open('file') as f:
for line in f:
print(re.findall('\d+', line))
Output:
['1', '2', '3', '4', '5']
['6', '7', '8', '9', '10']
['11', '12', '13', '14', '15']
['16', '17', '18', '19', '20']
['21', '22', '23', '24', '25']
Upvotes: 0
Reputation: 180401
You have strings not lists, you want convert to actual lists using ast.literal_eval
:
from ast import literal_eval
with open("grafik.txt") as f:
for line in f:
lst = literal_eval(line)
print(lst)
print(type(lst))
<class 'list'>
[6, 7, 8, 9, 10]
<class 'list'>
[11, 12, 13, 14, 15]
<class 'list'>
[16, 17, 18, 19, 20]
<class 'list'>
[21, 22, 23, 24, 25]
<class 'list'>
If you want a lists of lists change the code to:
lsts = [literal_eval(line) for line in f]
print(lsts)
If you really want floats for some reason you can use map to change the ints to floats but unless you specifically need floats I would not bother
lsts = [map(float, literal_eval(line)) for line in f] # list(map... python3
print(lsts)
Upvotes: 4