Reputation: 1
i have a file that is formatted as shown below:
2017-09-02 14:51:13,959 this is a sentence
2017-09-02 14:51:13,959 this is another sentence
2017-09-02 14:51:13,959 this is yet another a sentence
My end goal is to have an excel sheet with columns for date/time/sentence. to get there i am attempting to import the file as a list and then split each list item at the first two spaces. and then add each item to the end of a new list
ex:
2017-09-02
14:51:13,959
this is a sentence
this is the code i have been trying to get to work, but i cant get the split function to work.
file = input("drag log file here. ")
list1 = open(file).readlines()
for i in list1:
s = list1[i]
list2.append(s.split(" ",2)[2])
print(list2)
i keep getting all sorts of errors depending on what i try but currently its showing
Traceback (most recent call last):
s = str(list1[i])
TypeError: list indices must be integers or slices, not str
so i guess my question are:
what does this error mean and how do i attempt to fix it?
is there a better way to get to my end goal of the excel sheet?
would it be easier to modify the list into a csv file?
Upvotes: 0
Views: 46
Reputation: 77857
i
is a string, but you've used it as the index, rather than the contents. You need to be consistent in the way you use variables. Look at the error message again. It's not that you can't get split
to work: you can't access the contents in this fashion.
for s in list1:
list2.append(s.split(" ",2)[2])
or
for i in range(len(list1)):
s = list1[i]
list2.append(s.split(" ",2)[2])
Apply some basic debugging in the future. For instance, simply insert a print
to see that variable values are what you expect.
for i in list1: print (i, list1) # Check the values you're about to use. s = list1[i] list2.append(s.split(" ",2)[2])
Upvotes: 3