Python: (IndexError: list index out of range) readFile

Python: (IndexError: list index out of range) readFile

我在文本文件文件中得到了这段文字:

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

我想要这样

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

所以我尝试了这个代码

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")

第一种方法 getData 工作正常,但第二种方法不想工作.. 错误信息:

['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

file.txt

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

代码

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']

如果我没看错的话,_ 不是你文件的一部分。

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

使用生成器,解决方案如下:

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

如果 _ 是您文件的一部分,那么以下内容也将有效:

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