0

I got this text in a text file file:

_2015.9.30 - 15:36:3 , 13_
_2015.9.30 - 15:36:6 , 24_
_2015.9.30 - 15:36:8 , 33_

and I want to have it like this

_data=['2015.9.30 - 15:36:3', '2015.9.30 - 15:36:6', '2015.9.30 -15:36:8']_
_values=['13', '24', '33']_

so I tried this code

def getData(path):
   data = []

   readFile = open(path,'r')
   sepFile = readFile.read().split('\n')
   readFile.close()

   for i in sepFile:
       myData = i.split(',')
       data.append(myData[0])

   return data



def getValues (path):
   values = []

   readFile = open(path,'r')
   sepFile = readFile.read().split('\n')
   readFile.close()

   for i in sepFile:
       myValues = i.split(',')
       values.append(myValues[1])

   return values

print getData("mytext.txt")
print getValues("mytext.txt")

the first method getData works fine but the second one dont want to work .. errormessage:

['2015.9.30 - 15:36:3 ', '2015.9.30 - 15:36:6 ', '2015.9.30 - 15:36:8'] 

Traceback (most recent call last):
File "C:\Python27\z.NEW\schrottplatz.py", line 34, in <module>
print getValues("mytext.txt")
File "C:\Python27\z.NEW\schrottplatz.py", line 29, in getValues
values.append(myValues[1])
IndexError: list index out of range
2
  • are the _ really part of your data? Commented Sep 30, 2015 at 14:15
  • Check if you have a comma in every line in your file. Does it maybe contain empty lines, e.g. at the very end? The error occurs when the program tries to split a string containing no commas, resulting in a list with only one value, meaning that index 1 does not exist in it. Commented Sep 30, 2015 at 14:16

2 Answers 2

1

If I understood well, _ are not parts of your file.

2015.9.30 - 15:36:3 , 13
2015.9.30 - 15:36:6 , 24
2015.9.30 - 15:36:8 , 33

Using generators, a solution would be like this :

with open(path) as f:
    data, values = zip(*(line[:-1].split(" , ") for line in f.readlines()))

If _ are part of your file, then the following will also work :

with open(path) as f:
    data, values = zip(*(line[1:-2].split(" , ") for line in f.readlines()))
Sign up to request clarification or add additional context in comments.

Comments

0

file.txt

_2015.9.30 - 15:36:3 , 13_
_2015.9.30 - 15:36:6 , 24_
_2015.9.30 - 15:36:8 , 33_

code

with open('file.txt') as f:
    data = f.read().splitlines()

_data, _values = [], []
for d in data:
    val = d.split(' , ')
    _data.append(val[0][1:])
    _values.append(val[1][:-1])

print _data
print _values
#['2015.9.30 - 15:36:3', '2015.9.30 - 15:36:6', '2015.9.30 - 15:36:8']
#['13', '24', '33']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.