-1

I am trying to split a log files into a 2D list. First list splits at every tag and then at the second level it is split at every newline. I get the string and split it to get the first, but when I loop through it to split it again I get the error at the bottom. I have looked and tried different stuff with no luck. It seems right to me but I am fairly new to python.

with open('log.txt', 'r') as f:
     read_data = f.read().split('tag:         "')
f.closed

for i in read_data:
    print read_data[i].split()

Error:

File "parsing.py", line 6, in <module>
    print read_data[i].split()
TypeError: list indices must be integers, not str
luisfer
  • 125
  • 2
  • 10

3 Answers3

1
with open('log.txt', 'r') as f:
    data2D = [x.split() for x in f.read().split('tag:         "') ]
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
0

read_data is a list of strings. You then put each string of the list in turn into i. So far, so good. However, you then try to use i (which is a string) as an index. What you should do instead is:

print i.split()
khagler
  • 3,996
  • 29
  • 40
0

@Version 2 of your code:

Strings in Python are immutable. It means that they can never change - you can only make a new string with altered contents:

>>> x = "Foo\r\n"
>>> x
"Foo\r\n"
>>> x.rstrip("\r\n")
"Foo"
>>> x
"Foo\r\n"

As you can see rstrip() did not change the value of the string named x. Instead it returned an altered string. If you don't care about the previous value, you can just reassign the name x to the new one:

>>> x = x.rstrip("\r\n")
>>> x
"Foo"
lqc
  • 7,434
  • 1
  • 25
  • 25