Sunday, 18 August 2013

Parsing a text file into a list in python

Parsing a text file into a list in python

I'm completely new to Python, and I'm trying to read in a txt file that
contains a combination of words and numbers. I can read in the txt file
just fine, but I'm struggling to get the string into a format I can work
with.
import matplotlib.pyplot as plt
import numpy as np
from numpy import loadtxt
f= open("/Users/Jennifer/Desktop/test.txt", "r")
lines=f.readlines()
Data = []
list=lines[3]
i=4
while i<12:
list=list.append(line[i])
i=i+1
print list
f.close()
I want a list that contains all the elements in lines 3-12 (starting from
0), which is all numbers. When I do print lines[1], I get the data from
that line. When I do print lines, or print lines[3:12], I get each
character preceded by \x00. For example, the word "Plate" becomes:
['\x00P\x00l\x00a\x00t\x00e. Using lines = [line.strip() for line in f]
gets the same result. When I try to put individual lines together in the
while loop above, I get the error "AttributeError: 'str' object has no
attribute 'append'."
How can I get a selection of lines from a txt file into a list? Thank you
so much!!!

No comments:

Post a Comment